简体   繁体   中英

Lifetime of objects in c++

class Entity
{
  public:
    int a;
    Entity(int t)
      :a(t)
    {
        std::cout << "Constructor !" << std::endl;
    }
    ~Entity()
    {
        std::cout << "Destructor !" << std::endl;
    }

    Entity(Entity& o)
    {
        std::cout << "Copied !" << std::endl;
        this->a = o.a;
    }
};

Entity hi()
{
    Entity oi(3);
   return oi;
} 

int main()
{
  {
        Entity o(1);
        o = hi();
  }
     std::cin.get();
}

OUTPUT:

Constructor !

Constructor !

Copied !

Destructor !

Destructor !

Destructor !


I created two objects and I copied one, So three constructors and three destructors.

Your "Copied!" line in the output is coming from the copy constructor, so you're creating three objects, not just two (then you're destroying all three, as expected).

Note that a copy constructor should normally take its argument by const reference. At a guess, you may be using Microsoft's C++ compiler, which will bind a temporary to a non-const reference.

Also note that if you turn on optimization, you can probably expect to see just two constructors and two destructors, with no copy construction happening. With a new enough (C++17) compiler, that should happen even if you don't turn on optimization (copy elision has become mandatory).

This is a trivial question

Can any one explain the reason for three destructor?

when you call

o=hi();

your function is called which makes an object of type Entity , which in return calls the constructor. This is where you get one extra constructor message

Replace your Entity(int t) contructor by this

 Entity(int t)
   :a(t)
  {
    std::cout << "Constructor created with integer "<< a << std::endl;
  }

You will see which constructors were called when you run the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM