Exception: access violation

What is wrong with this code below and how to fix it.

#include<iostream> using namespace std; template<typename Func1, typename Func2> class guard{ public: guard(Func1 first, Func2 last) : last(last){ first(); } ~guard(){ last(); } private: Func2& last; }; template<typename Func1, typename Func2> guard<Func1, Func2> make_guard(Func1 first, Func2 last){ return guard<Func1, Func2>(first, last); } void first(){ cout << "first" << endl; } void last(){ cout << "last" << endl; } int main(){ { first(); // ok last(); // ok auto g = make_guard(first, last); first(); //exception: Access violation last(); //exception: Access violation } first(); // ok last(); // ok cin.get(); } 

The function first() and last() cannot be called before the expiration of the variable g . Compiled in VC ++ 2012 and got the same problem both in debug mode and in release mode.

+4
source share
1 answer

Your guard contains a link, but it takes a value. The reference becomes invalid as soon as the guard constructor ends, since it refers to the last parameter accepted by the constructor, and not to the parameter passed to make_guard .

After accessing an invalid link, you have undefined behavior and all bets are disabled.

+5
source

All Articles