c++ - Returning a braced initializer list from a function: What is it compiled down to? -


here's small piece of code example.

#include <iostream>  struct coordinate {     int x, y; };  coordinate shift(coordinate p, int offset) {     return {p.x + offset, p.y + offset}; }  int main(int argc, char *argv[]) {     coordinate p {1, 2};     coordinate p_s = shift(p, 3);     std::cout << "x: " << p_s.x << "\ty: " << p_s.y;     return 0; } 

in function shift, see return statement seemingly returning initializer list.

while understand means semantically, i'm looking confirm if understand compiled down to.

does compiler interpret shift function this?

shift(coordinate p, int offset) {     coordinate p_ {p.x + offset, p.y + offset};     return p_; } 

if not, how?

thanks help.

it similar, although seems more natural write equivalence constructor expression:

 return coordinate{p.x + offset, p.y + offset}; 

which makes obvious not more syntactic sugar. is, not returning initializer list, rather returning new object of indicated type constructed using braced-init-list syntax.

note copy elision applies, when return value assigned newly constructed coordinate, intermediate coordinate not constructed (or might not constructed, in older c++ versions).


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -