Y
yinglcs
I am reading the Boost scoped_ptr library, and I wonder what is the
advantage of using that.
Here is an example from Boost.org web site:
#include <boost/scoped_ptr.hpp>
#include <iostream>
struct Shoe { ~Shoe() { std::cout << "Buckle my shoe\n"; } };
class MyClass {
boost::scoped_ptr<int> ptr;
public:
MyClass() : ptr(new int) { *ptr = 0; }
int add_one() { return ++*ptr; }
};
int main()
{
boost::scoped_ptr<Shoe> x(new Shoe);
MyClass my_instance;
std::cout << my_instance.add_one() << '\n';
std::cout << my_instance.add_one() << '\n';
}
can't I simple change code to allocate the 'Shoe' object from the stack
instead of getting it from the heap, like this:
int main()
{
Shoe shoe;
MyClass my_instance;
std::cout << my_instance.add_one() << '\n';
std::cout << my_instance.add_one() << '\n';
}
since we don't pass scoped_ptr outside the function (that is the
functionality of Boost shared_ptr), I don't the advantage of using
Boost scoped_ptr.
Thank you.
advantage of using that.
Here is an example from Boost.org web site:
#include <boost/scoped_ptr.hpp>
#include <iostream>
struct Shoe { ~Shoe() { std::cout << "Buckle my shoe\n"; } };
class MyClass {
boost::scoped_ptr<int> ptr;
public:
MyClass() : ptr(new int) { *ptr = 0; }
int add_one() { return ++*ptr; }
};
int main()
{
boost::scoped_ptr<Shoe> x(new Shoe);
MyClass my_instance;
std::cout << my_instance.add_one() << '\n';
std::cout << my_instance.add_one() << '\n';
}
can't I simple change code to allocate the 'Shoe' object from the stack
instead of getting it from the heap, like this:
int main()
{
Shoe shoe;
MyClass my_instance;
std::cout << my_instance.add_one() << '\n';
std::cout << my_instance.add_one() << '\n';
}
since we don't pass scoped_ptr outside the function (that is the
functionality of Boost shared_ptr), I don't the advantage of using
Boost scoped_ptr.
Thank you.