简体   繁体   English

C++中对象的生命周期

[英]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.请注意,复制构造函数通常应通过const引用来获取其参数。 At a guess, you may be using Microsoft's C++ compiler, which will bind a temporary to a non-const reference.猜测,您可能正在使用 Microsoft 的 C++ 编译器,它将临时引用绑定到非常量引用。

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).使用足够新的 (C++17) 编译器,即使您不打开优化(复制省略已成为强制性),也应该发生这种情况。

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.您的函数被调用,它生成一个 Entity 类型的对象,它反过来调用构造函数。 This is where you get one extra constructor message这是您获得一条额外构造函数消息的地方

Replace your Entity(int t) contructor by thisEntity(int t) contructor by this替换你的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.您将看到运行代码时调用了哪些构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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