如下代码的输出,在vs2017和网上编译器都是一样的,留存看看以后能不能解惑
#include <iostream> #include <memory> #include <string> using namespace std; int g_constructNum = 0; int g_copyConstructNum = 0; int g_moveConstructNum = 0; int g_deleteNum = 0; class MyTestString { private: std::string m_data; int m_value; void test() {} public: MyTestString(std::string data,int value) :m_data(data),m_value(value) { std::cout << "construct: " << ++g_constructNum << std::endl; } MyTestString(const MyTestString& myTestString) { m_data = myTestString.m_data; m_value = myTestString.m_value; std::cout << "copy construct: " << ++g_copyConstructNum << std::endl; } MyTestString(MyTestString &&myTestString) { std::swap(m_data, myTestString.m_data); std::swap(m_value, myTestString.m_value); std::cout << "move copy construct: " << ++g_moveConstructNum << std::endl; } ~MyTestString() { std::cout << "destruct: " << ++g_deleteNum << std::endl; } }; MyTestString getTempString() { MyTestString temp("tangmiao", 1); return temp; } int main() { //MyTestString temp = getTempString(); MyTestString temp(MyTestString("tangmiao",1)); return 0; }
按道理应该是输出:
construct: 1
move copy construct: 1
destruct: 1
destruct: 2
而输出的是: