c++ - will move semantics prevent copying here? -
// --- move constructor matrix(matrix&& other) throw() : data_(other.data_), rows_(other.rows_), columns_(other.columns_) { other.rows_ = other.columns_ = 0; other.data_ = nullptr; } // --- move assignment matrix & operator=(matrix&& other) throw() { using std::swap; swap(rows_, other.rows_); swap(columns_, other.columns_); swap(data_, other.data_); return *this; }
multiplyadd
implementation:
template <class t> matrix<t> multiplyadd(const t a,const matrix<t> &x,const t b) { matrix<t> out(a*x+b); return out; } template <class t> matrix<t> multiplyadd(const matrix<t> a,const matrix<t> &x,const t b) { matrix<t> out(a*x+b); return out; } int main(){ matrix<> x = // initialization auto&& temp_auto = multiplyadd(a,x,b); (int = 1; < n-1; i++) { temp_auto = multiplyadd(temp_auto,temp2,b); } return 0; }
question: use of auto
keyword in last code snippet avoid creation of temporaries? before , more important inside 'for' loop.
will use of
auto
keyword in last code snippet avoid creation of temporaries?
no. temporary needs created anyway, since temp_auto
reference, , there must reference bound to.
your odds avoid creation of temporary higher if had done:
auto temp_auto = multiplyadd(a,x,b);
in case compiler perform copy/move elision , construct result of multiplyadd()
directly temp_auto
, without having call move constructor.
the reason talking "odds" per paragraph 12.8/31 of c++11 standard, compiler entitled, not obliged, perform copy/move elision.
to clarify going on, try explain compiler has when returning object. consider simple function , subsequent function call:
x foo() { x x; /* ... */ return x; } // ... x y = foo();
here, when returning x
, compiler have to:
- move-construct temporary
x
(let's callt
); - move-construct
y
t
.
now copy elision, compiler allowed avoid creation of temporary t
, construct returned object x
directly in y
, , elide both calls move constructor.
on other hand, inside loop:
temp_auto = multiplyadd(temp_auto,temp2,b);
you doing assignment. in our simple example, equivalent of:
x foo() { x x; /* ... */ return x; } // ... x y; y = foo();
even here, when returning x
foo()
, compiler has to:
- move-construct temporary
x
foo()
(let's callt
again); - move-assign
t
y
.
even in case, creation of temporary can avoided passing directly x
(instead of t
) move-assignment operator assigns y
, although call move-assignment operator cannot elided (only calls copy/move constructors can elided).
notice, true both in original example (where temp_auto
reference) , in modified example above, temp_auto
object of class type.
Comments
Post a Comment