Why is the copy constructor being called before deleting the object?

I have the following class, which includes a copy constructor:

Header File: 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

};


}

Implementation File: Fred.cpp

#include "Fred.h"
#include <iostream>

foo::Fred::Fred(){
    _x = 0;
    _y = 0;

    std::cout << "Calling the default constructorn";
}

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 constructorn";
}

foo::Fred::~Fred(){

    std::cout << "Goodbye, cruel world!n";
}

I was expecting to see the destructor called when it got out of scope, instead, the copy constructor was called and then the destructor. Why was a copy created? Am I leaking memory?

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;
}

That's because you're using the memory leak operator *new .

Objects allocated with new are never deleted automatically; only by an explicit use of delete . Your code dynamically allocates an object, copies it to f2 , and then loses the only pointer to the dynamic object.

If you simply want to create a local object:

Fred f2;

When you actually need dynamic allocation (in other words, if the object needs to outlive the current scope), always use RAII objects, such as smart pointers, to avoid memory leaks. For example:

std::unique_ptr<Fred> f2(new Fred);   // C++11 - no "delete" needed
auto f2 = std::make_unique<Fred>();   // C++14 - no "new" or "delete" needed

Yes, the code leaks memory: new Fred() allocates an object on the heap, but the code doesn't save the returned pointer and doesn't delete the object.

The reason the copy constructor is called is that the creation of f2 copies the argument, just as if it had been written

Fred f2(*new Fred());

What you probably meant to write was:

Fred f2 = Fred();

And since Fred has a user-defined default constructor, you can shorten that to:

Fred f2;
链接地址: http://www.djcxy.com/p/96542.html

上一篇: 管理STL向量中的范围和对象生命周期

下一篇: 为什么在删除对象之前调用拷贝构造函数?