Sunday, 15 April 2012

c++ - Get notified when object goes out of scope/gets invalid -



c++ - Get notified when object goes out of scope/gets invalid -

i have vector class can homecoming slices of itself. slices reference actual vector both piece , origin modified. problem next codesnippet:

class vectorbase { // offers basic methods } class vector : vectorbase { // actual vector } class vectorref : vectorbase { // references parts of vector // constructor creates piece of base of operations vector vectorref(vectorbase base, int start, int end); } void foo () { vector* = new vector(); vectorref b(*a, 1,4); delete a; b.length(); // <---- problem because isn't valid anymore }

the way want solve throwing exceptions when user calls methods on piece object. how can determine whether or not original object got out of scope?

there couple of ways of solving this.

if have access c++11 or boost 1 way utilize shared , weak pointers. forcefulness instantiate vectors shared pointers don't have implement own referencing scheme. implies vectorref not own vector.

class vectorref : vectorbase { // references parts of vector // constructor creates piece of base of operations vector vectorref(std::shared_ptr<vectorbase> base, int start, int end) : m_base(base), m_start(start), m_end(end) { } std::weak_ptr<vectorbase> m_base; length() override { if (auto base of operations = m_base.lock()) { // has copied shared_ptr before usage { homecoming m_end-m_start; } else { trow(vectorexception("base has expired")); } } } void foo () { std::shared_ptr<vector> = std::make_shared<vector>(); vectorref b(a, 1,4); a.reset(); b.length(); // throw exception }

c++ reference

No comments:

Post a Comment