简体   繁体   中英

Constructors, destructors and ternary operator

I have this simple class with two specialized constructors.

#include <iostream>

class test_01
{
  std::string name;
  uint16_t value;
public:
  test_01(std::string name);
  test_01(uint16_t value);
  ~test_01();
  void show_message(std::string message);
};

test_01::test_01(std::string name)
{
  std::cout << "Constructor string is called" << std::endl;
  test_01::name = name;
}

test_01::test_01(uint16_t value)
{
  std::cout << "Constructor uint16 is called" << std::endl;
  test_01::value = value;
}

test_01::~test_01()
{
  std::cout << "Destructor is called" << std::endl;
}

void test_01::show_message(std::string message)
{
  std::cout << message.c_str() << std::endl;
}


int main()
{
  bool result = true;

  test_01 t = result ? test_01("test") : test_01(57);
  t.show_message("hello");
}

Each constructor is called depending on an external condition. When the ternary operator is executed a destructor is called. Thus.

Constructor string is called

Destructor is called

hello

Destructor is called

I don't understand why the first destructor is called

Thanks !

Because there are two test_01 objects created, so two must be destroyed.

                     first is exactly one of
                     vvvvvvvvvvvvvvv or  vvvvvvvvvvvv
test_01 t = result ? test_01("test")  :  test_01(57);
        ^ second is here

Had you added logging to the copy or move constructors, you would see, a temporary object is copied/moved into t object, which is move/copy constructed from this temporary.

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