Bo Yang wrote:
As long as I write c++ code, I am worry about the
pointer. The more the system is, the dangerous the pointer
is I think.
I must pass pointers erverywhere, and is there a way to
ensure that every object pointered by any pointer will
be deleted and only be deleted once?
Your goal is to write an entire program without using a pointer
directly. Not even one.
Note that references do just fine if polymorphism is required.
Its easier than you think. Since no naked pointers means no bugs and no
aspirins.
Replace any allocation with the appropriate smart pointer and use STL
containers (which support copy semantics).
Replace pointers with references, prefereably - const references where
appropriate.
#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <boost/shared_ptr.hpp>
template< typename T >
class A {
T t;
public:
// ctor
A(const T& val = T()) : t(val)
{
std::cout << "A()\n";
}
// copy ctor
A(const A& copy)
{
std::cout << "copy A\n";
t = copy.t;
}
// d~tor
~A() { std::cout << "~A()\n"; }
// friend op<<
friend std::ostream&
operator<<(std: :ostream& os, const A& r_a)
{
return os << r_a.t;
}
};
int main() {
{
std::vector< A< double vd(5, 11.1); // 5 elements
std::copy( vd.begin(),
vd.end(),
std::ostream_it erator< A< double (std::cout, "\n") );
}
std::cout << "allocating using shred_ptr...\n" ;
boost::shared_p tr< A< std::string sp_a(new A< std::string >("a
short string"));
std::cout << *sp_a << std::endl;
return 0;
}
/*
A() < -temp
copy A
copy A
copy A
copy A
copy A
~A() <- temp destruction
11.1
11.1
11.1
11.1
11.1
~A() <- 5 automatic destructors
~A()
~A()
~A()
~A()
allocating using shred_ptr...
A()
a short string
~A() <- automatic
*/
And if you have any doubt about the strategy, change
std::vector< A< double vd(5, 11.1); // 5 elements
to
std::vector< A< double vd(1000000); // one million
For the sake of comparison: the equivalent of a const reference is a
const pointer to a const value.
int n;
const r_n&(n);
const p_n* const(&n);
Using pointers is iffy enough, using non-const pointers can be
downright dangerous where these should be immutable.