c++ - Is this a way to defeat elision to keep dtor side effects? -


i make sure destructor side effects retained in function candidate rvo. goal snapshot stack @ entry , exit , have expected stack variables present. code seems work c++11 without using compiler specific options don't know way in earlier versions without adding spurious instances of test create multiple return paths. there technique , work c++11?

class test { public:     int m_i;     test() { m_i = 0; cout << "def_ctor" << endl; }     test(const test& arg) { this->m_i = arg.m_i; cout << "copy_ctor" << endl;}     ~test() { cout << "dtor needed side effects" << endl; } };  test foo() {     test ret;     return std::move(ret); }  int main() {     test x=foo(); } 

std::move isn't magic, it's function returns reference argument, should able same in version of c++

template<typename t>   const t&   defeat_rvo(const t& t)   { return t; }  test foo() {     test ret;     return defeat_rvo(ret); } 

i think can more directly, returning reference:

test foo() {     test ret;     const test& ref = ret;     return ref; } 

the copy elision rules local object can constructed directly in return value when expression in return statement "the name of non-volatile automatic object", not case here, it's reference object, not name of object itself. i'm less case, cast should work:

test foo() {     test ret;     return static_cast<const test&>(ret); } 

this isn't name of object, or name of alias object, it's cast expression.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -