Thank you very much for your immediate response Uli and Alf P.Steinbach.
I am workning with VC++ 6.0. Seems to be shared_ptr is from boost C++
library. How can I use boost library in VC++ 6.0? I think, MS supports
std::tr1::shared_ptr with visual studio 2008. shared_ptr supports vc6.0?
Thanks in advance.
Alex.
"Alf P. Steinbach" wrote:
* Alex:
Hi all,
Please find the below code snippet. There, I deleted memory in main()
function as well as destructor of TestPointer. How to find whether that
resource is already deleted or not?
Generally, you can't.
Instead, you can guarantee that except for circular data structures, resources
are automatically released.
Can I achieve it by using smart pointers...
>
#include "stdafx.h"
class TestPointer
{
private:
int* m_pInts;
public:
TestPointer():m_pInts(0){}
~TestPointer(){delete[] m_pInts;}
SetPointer(int* ptrInts){m_pInts = ptrInts;}
};
int main(int argc, char* argv[])
{
int* pints = new int[100];
TestPointer obj1, obj2, obj3;
obj1.SetPointer(pints);
obj2.SetPointer(pints);
obj3.SetPointer(pints);
//stmt...1
//........
//........
//stmt...n
delete[] pints;
return 0;
}
Off-the-cuff lightweight solution (assuming that the above example does
illustrate your intent, that it's not just a case of a locally scoped array):
#include <boost/shared_array.hpp>
typedef boost::shared_array<int> IntArrayPtr;
class TestPointer
{
private:
IntArrayPtr myInts;
public:
void setPointer( IntArrayPtr p ) { myInts = p }
};
int main()
{
IntArrayPtr ints( new int[100] );
TestPointer obj1, obj2, obj3;
obj1.setPointer( ints );
obj2.setPointer( ints );
obj3.setPointer( ints );
// statements, no explicit delete.
}
Off-the-cuff more heavy duty solution, supporting e.g. dynamic size changes:
#include <vector>
#include <boost/shared_ptr.hpp>
typedef std::vector<int> IntVec;
typedef boost::shared_ptr<IntVec> IntVecPtr;
class TestPointer
{
private:
IntVecPtr myInts;
public:
void setPointer( IntVecPtr p ) { myInts = p }
};
int main()
{
IntVecPtr ints( new IntVec( 100 ) );
TestPointer obj1, obj2, obj3;
obj1.setPointer( ints );
obj2.setPointer( ints );
obj3.setPointer( ints );
// statements, no explicit delete.
}
Possible design issue: 'setPointer' means that a TestPointer object starts out
life without a valid pointer. That complicates all operations. If the problem
requirements allow it would be better to establish a valid pointer in the
constructor and not have a 'setPointer' member function.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?