我有以下类,其中包括一个复制构造函数:
头文件: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;
}