Is it a way to defeat elite in order to preserve the side effects of dtor?

I would like to make sure that the side effects of the destructor are stored in a function that is a candidate for RVO. My goal is to take a snapshot of the stack on entry and exit and have the expected stack variables. This code seems to work for C ++ 11 without using special options for the compiler, but I don't know how to do it in earlier versions without adding false instances of Test to create multiple return paths. Is there some kind of technique and this always works for 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 for side effects" << endl; }
};

Test foo() {
    Test ret;
    return std::move(ret);
}

int main()
{
    Test x=foo();
}
+4
source share
2 answers

std::move , , , ++

template<typename T>
  const T&
  defeat_rvo(const T& t)
  { return t; }

Test foo() {
    Test ret;
    return defeat_rvo(ret);
}

, , :

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

, , return " ", , , . , :

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

, , .

+2

, ; .

, , ; , , .

(template<class T> T copy_of(T const& t){return t;}, return copy_of(whatever);, static_cast, - ). , , .

+1

All Articles