ヒープで作成されたオブジェクトへの参照を返す際に助けが必要です。Sam's Teach Yourself C++ というタイトルの本を読んでいます。第 12 章で、著者はヒープ上のオブジェクトへの参照を返すことを紹介しています。この例はメモリ リークを示しており、作成者によると、解決策の 1 つは、呼び出し元の関数でオブジェクトを宣言し、それを参照によって TheFunction() に渡すことです。
これは例です:
// Listing 12.5
// Resolving memory leaks
#include <iostream>
class SimpleCat
{
public:
SimpleCat (int age, int weight);
~SimpleCat() {}
int GetAge() { return itsAge; }
int GetWeight() { return itsWeight; }
private:
int itsAge;
int itsWeight;
};
SimpleCat::SimpleCat(int age, int weight):
itsAge(age), itsWeight(weight) {}
SimpleCat & TheFunction();
int main()
{
SimpleCat & rCat = TheFunction();
int age = rCat.GetAge();
std::cout << "rCat is " << age << " years old!\n";
std::cout << "&rCat: " << &rCat << std::endl;
// How do you get rid of that memory?
SimpleCat * pCat = &rCat;
delete pCat;
// Uh oh, rCat now refers to ??
return 0;
}
SimpleCat &TheFunction()
{
SimpleCat * pFrisky = new SimpleCat(5,9);
std::cout << "pFrisky: " << pFrisky << std::endl;
return *pFrisky;
}
私の試み:
#include <iostream>
class SimpleCat
{
public:
SimpleCat(int age, int weight);
~SimpleCat() {}
int GetAge() { return itsAge; }
int GetWeight() { return itsWeight; }
private:
int itsAge;
int itsWeight;
};
SimpleCat::SimpleCat(int age, int weight):
itsAge(age), itsWeight(weight) {}
SimpleCat* TheFunction(SimpleCat&);
int main()
{
SimpleCat * rCat;
rCat = TheFunction(rCat);
int age = rCat->GetAge();
std::cout << "rCat is " << age << " years old!\n";
std::cout << "rCat: " << rCat << std::endl;
delete rCat;
rCat = 0;
system("PAUSE");
return 0;
}
SimpleCat* TheFunction(SimpleCat& rCat)
{
rCat = new SimpleCat(5, 9);
std::cout << "rCat: " << rCat << std::endl;
return rCat;
}
2 回目の試行
#include <iostream>
using namespace std;
class SimpleCat
{
public:
SimpleCat(int age, int weight)
{
}
void setAge(int age)
{
itsAge = age;
}
void setWeight(int wgt)
{
itsWeight = wgt;
}
~SimpleCat() { cout << "Object is being deleted" << endl; }
int GetAge() { return itsAge; }
int GetWeight() { return itsWeight; }
private:
int itsAge;
int itsWeight;
};
//SimpleCat * TheFunction();
SimpleCat& TheFunction(SimpleCat* rCat)
{
rCat = new SimpleCat(5,9);
//pFrisky->setAge(5);
//pFrisky->setWeight(9);
return *rCat;
}
int main()
{
SimpleCat * rCat;
SimpleCat & rCat = TheFunction(&rCat);
int age = rCat.GetAge();
std::cout << "rCat is " << age << " years old!\n";
system("PAUSE");
return 0;
}