f******y 发帖数: 2971 | 1 In the following program, obviously there is a memory leak. Other than that,
I see memory newed in the main function is deleted twice. When I ran it, it
did not crash however. Anybody can explain it? Thanks
#include
class Ctest {
public:
Ctest(){}
~Ctest(){}
double m_value[200];
};
void function(Ctest* test) {
delete test;
test = new Ctest();
}
int main() {
Ctest* t = new Ctest();
function(t);
delete t;
return 0; |
|
d***r 发帖数: 2032 | 2 下面这个code有错,因为m_value是const,不能赋值。能不能保留m_value的const属性
作其他改动使得code能够work呢?
class cTest
{
public:
cTest():{};
~cTest(){};
void SetValue( const double val ) const
{
m_value = val;
}
private:
double m_value;
};
int main( void )
{
cTest *t = new cTest();
t->SetValue(100);
delete t;
} |
|
K*****n 发帖数: 65 | 3 members can not be initialized in class DEFINITION.They need to be
initialized via constructor.
Instead of
class CTest
{
public:
CTest(){};
private:
int nX(0);
};
You will need
class CTest
{
public:
CTest:nX(0){};
private:
int nX(0);
};
When you change vector to array, then it is OK because array
is declaration.To achieve what you intended:
class example{
public:
static const int vecSize = 10;
example(){vec.resize(vecSize);};
std::vector vec; |
|
d*****d 发帖数: 46 | 4 interesting, try this
void function(Ctest* test) {
delete test;
Ctest* test1 = new Ctest();
test = new Ctest();
delete test1;
}
you may see why...
that,
it |
|
z****e 发帖数: 2024 | 5 void function(Ctest*& test)
这样才行。 |
|