C++ Assignment strange behaviour -



C++ Assignment strange behaviour -

could explain me output of next code? variable changes it's value @ end of assignment.

#include <iostream> #include <new> using namespace std; template<class crtp> class object_t { public: object_t<crtp> &operator=(const object_t<crtp> &a) { ((crtp*)this)->~crtp(); new ((crtp*)this) crtp(*(const crtp*)&a); cout << "value in assignment: " << ((crtp*)this)->n << endl; homecoming *this; } }; class darr_t : public object_t<darr_t> { public: int n; darr_t(const darr_t &a) : n(a.n + 1) { cout << "value in constructor: " << n << endl; } darr_t(int pn) : n(pn) {} }; int main() { darr_t tmp(42); darr_t tmp2(55); tmp = tmp2; cout << "value in main: " << tmp.n << endl; homecoming 0; }

output:

value in constructor: 56 value in assignment: 56 value in main: 55

expected output:

value in constructor: 56 value in assignment: 56 value in main: 56

edit: @cheersandhth.-alf , @mr_hic-up answers! problem default darr_t::operator= first calls base of operations type's assignment after calls assignment(overrides) members of darr_t object!

you observing behavior because:

the compiler defines implicit re-create assignment operator darr_t. the implicit re-create assignment calls re-create assignment operator of base of operations class first before performing re-create assignment of fellow member variables.

here's relevant documentation http://en.cppreference.com/w/cpp/language/as_operator:

implicitly-declared re-create assignment operator

if no user-defined re-create assignment operators provided class type (struct, class, or union), compiler declare 1 inline public fellow member of class. implicitly-declared re-create assignment operator has form t& t::operator=(const t&) if of next true:

each direct base of operations b of t has re-create assignment operator parameters b or const b& or const volatile b&

each non-static info fellow member m of t of class type or array of class type has re-create assignment operator parameters m or const m& or const volatile m&

otherwise implicitly-declared re-create assignment operator declared t& t::operator=(t&). (note due these rules, implicitly-declared re-create assignment operator cannot bind volatile lvalue argument)

c++ variable-assignment copy-constructor

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -