C++ C+有什么问题+;匿名对象?
我写了这样一个简单的代码:C++ C+有什么问题+;匿名对象?,c++,C++,我写了这样一个简单的代码: class Test { public: Test() { cout << "Constructor called." << endl; } ~Test() { cout << "Destructor called." << endl; } Test(const Test& test) { cout
class Test
{
public:
Test()
{
cout << "Constructor called." << endl;
}
~Test()
{
cout << "Destructor called." << endl;
}
Test(const Test& test)
{
cout << "Copy constructor called." << endl;
}
void Show() const
{
cout << "Show something..." << endl;
}
};
Test Create()
{
return Test();
}
int main()
{
Create().Show();
}
Test Create()
{
Test test;
return test;
}
但当我修改函数Create()时,如下所示:
class Test
{
public:
Test()
{
cout << "Constructor called." << endl;
}
~Test()
{
cout << "Destructor called." << endl;
}
Test(const Test& test)
{
cout << "Copy constructor called." << endl;
}
void Show() const
{
cout << "Show something..." << endl;
}
};
Test Create()
{
return Test();
}
int main()
{
Create().Show();
}
Test Create()
{
Test test;
return test;
}
输出为:
Constructor called.
Copy constructor called.
Destructor called.
Show something...
Destructor called.
为什么匿名对象不调用复制构造函数和析构函数?请帮助我,谢谢。这是调用。在这两种情况下,都允许省略副本;出于某种原因,编译器在第一种情况下执行此操作,但在第二种情况下不执行此操作。(调试模式下的MSVC显然决定有时不这样做)
注意,当你说“匿名类”时,你指的是临时对象。“匿名类”的意思不同。请阅读。这里有匿名类,而不是OP所想的。@C.R.OP的代码中没有匿名类。唯一的类有一个名称,
Test
。