MS Visual C++ 2010 Error: On provision of default destructor
I am getting run-error on providing default destructor. However, if left to compiler to provide default destructor it is running safely.
class foo
{
private:
int m_size;
int* m_array;
public:
foo( int a_size ):m_size( a_size ), m_array( new int(a_size) ){}
~foo() {
delete [] m_array;
}
void setArray();
};
void foo::setArray()
{
for( int i=0; i<m_size; ++i )
m_array[i] = 10*i;
}
int main( int argc, const char* argv[] )
{
class foo obj( 6 );
obj.setArray();
system( "pause" );
return开发者_开发技巧 0;
}
Runtime Error:
This may be due to a corruption of the heap, which indicates a bug in Destructors.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while Templates.exe has focus.
The output window may have more diagnostic information.
Thanks.
new int(a_size)
dynamically allocates a single int
with initial value a_size
.
I think you mean new int[a_size]
which dynamically allocates an array of a_size
int
s.
(You should also provide a copy constructor and copy assignment operator for your foo
class as the default ones will not do the correct thing. Better would be to replace your pointer member m_array
with a std::vector<int>
to manage the dynamically allocated memory automatically and then you wouldn't have to worry about a user-defined destructor, copy constructor and copy assignment operator.)
You allocated a single int
, and then tried to delete an array.
The proper way to allocate an array of int
s is:
new int[a_size]
Note the square (array) brackets, not parentheses.
As always, you should follow the rule of three and define a copy constructor as well.
EDIT: showing my preferred style:
class Foo
{
int m_size;
int* m_array;
public:
Foo( int const a_size )
: m_size(a_size)
, m_array(new int[a_size])
{}
~Foo( void )
{
delete [] m_array;
}
void setArray(void);
};
void Foo::setArray( void )
{
for( int i = 0; i < m_size; ++i )
m_array[i] = 10*i;
}
int main( void )
{
Foo obj(6);
obj.setArray();
system("pause");
return 0;
}
精彩评论