What is the objective of scoped pointer? to my understanding, the scoped pointer manages the memory within a block of code. If i want to declare a variable within a block , i can just declare it on a stack and not worry about cleaning.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
usually thread stacks have memory limits (see thread stacksize).
also sometimes the pointer might have been passed to you from outside and needs to be deleted in this scope (e.g. if an exception is thrown, any delete call below that line won't get executed). So you need someway of auto-magically cleaning up the pointer
Not if it's of dynamic size or type. In addition, scoped pointers can be swapped, and in C++11
unique_ptr
can be moved, so they're not strictly scoped.Unlike stack-based data, scoped_ptr has a reset() member -- in other words, you can construct/destruct to your heart's content. With this, you can use a null pointer (technically
operator unspecified-bool-type
) as a flag indicating whether or not there is a constructed object at any given time. It also allows you to sequence construction/destruction independently from the variable scope if that is needed.Also, consider that you can declare a scoped_ptr as a class member, not just as a stack variable. The docs suggest using scoped_ptr to implement the handle/body idiom (to hide the class' implementation details).
Finally, to elaborate on DeadMG's point "Not if it's of dynamic type", you can use scoped_ptr to implement a polymorphic operation:
It's not really possible to do this with simple stack-based allocation.
Also see here: C++0x unique_ptr replaces scoped_ptr taking ownership?
The point is that you can create and clean up a pointer within a certain lexical scope. This can be useful in a variety of situations, and it assures you have no memory leaks, by forgetting a
delete
if you were to usenew
explicitly, which is not recommended.You should keep in mind that the
boost::scoped_ptr
is non-copyable, and so owns it's resource entirely, for the entire duration of it's lifetime. This also makes it safer thenboost::shared_ptr
, as it avoids copying the resource or accidentally sharing it.