c++ - How to use auto_ptr in this case -
i have following code:
void do_something(image *image) { image *smoothed = null; image *processed = null; if (condition_met) { smoothed = smooth(image); processed = smoothed; } else { processed = image; } ... delete smoothed_image }
i wondering if can following , if correct way. confused setting pointer auto_ptr object , whether changes ownership somehow.
void do_something(image *image) { auto_ptr<image *> smoothed; image *processed = null; if (condition_met) { smoothed = smooth(image); // should own pointer returned smooth processed = smoothed; // ok? processed not auto_ptr } else { processed = image; } ... // destructor 'smoothed' variable should called. // 'image' variable not deleted. }
will destructor called intend , correct way this?
a few points make. assuming signature of smooth function
image* smooth(image*);
then code minimally have changed to
void do_something(image *image) { auto_ptr<image> smoothed; image *processed = null; if (condition_met) { smoothed.reset(smooth(image)); // should own pointer returned smooth processed = smoothed.get(); // maybe? depends on you're doing } else { processed = image; }
it's reasonable in cases pull raw pointer out of smart pointer done in smoothed.get()
above, have understand written pointer held smoothed deleted @ end of function, though you've done else raw pointer. not enough information here see if that's problem, it's smell.
std::auto_ptr deprecated in favor of std::unique_ptr. big reason way contents of auto_ptr moved:
std::auto_ptr<int> = new int(5); std::auto_ptr<int> b = a; // copy? no!
in code pointer held has been transferred b. a no longer holding anything. runs counter how think of copy behavior it's easy mess up.
c++11 introduced concept of r-value references (there loads of articles around net explaining this, including what move semantics?). having r-value references allows unique_ptr prevent data being moved doesn't make sense.
std::unique_ptr<int> = new(5); std::unique_ptr<int> b = a; // compile fail. not copyable std::unique_ptr<int> c = std::move(a); // ok, shows intent
with available, possible update smooth() function signature to
std::unique_ptr<image> smooth(image*) { ... return newimage; }
which instructs caller should take ownership of of returned pointer. can say
unique_ptr<image> smoothed; ... smoothed = smooth(image);
because value returned function r-value (not bound variable yet), pointer safely moved smoothed.
in end, yes, using smart pointer preferable calling delete. think through design , try clear pointer ownership.
Comments
Post a Comment