コピーコンストラクターを含む次のクラスがあります。
ヘッダー ファイル: Fred.h
namespace foo {
class Fred {
private:
int _x;
int _y;
public:
Fred(); // Default constructor
Fred(Fred const &other); // Copy constructor
Fred(int x, int y); // Regular parameters
~Fred(); // Destrcutor
};
}
実装ファイル: Fred.cpp
#include "Fred.h"
#include <iostream>
foo::Fred::Fred(){
_x = 0;
_y = 0;
std::cout << "Calling the default constructor\n";
}
foo::Fred::Fred(Fred const &other){
_x = other._x;
_y = other._y;
std::cout << "Calling the copy constructor";
}
foo::Fred::Fred(int x, int y){
_x = x;
_y = y;
std::cout << "Calling the convenience constructor\n";
}
foo::Fred::~Fred(){
std::cout << "Goodbye, cruel world!\n";
}
スコープ外になったときにデストラクタが呼び出されることを期待していましたが、代わりに、コピー コンストラクタが呼び出され、次にデストラクタが呼び出されました。なぜコピーが作成されたのですか?私はメモリをリークしていますか?
using namespace foo;
int main(int argc, const char * argv[])
{
{
Fred f2 = *new Fred();
} // I was expecting to see a destructor call only
return 0;
}