尝试运行此code,以查看如何在单个表达式中调用匿名对象ctor / dctor:
#include <math.h>
#include <iostream>
using namespace std;
class Test {
public:
int mA = 0;
Test() {
mA = 1000;
cout << "ctor test" << endl;
}
~Test() {
cout << "dctor test" << endl;
}
};
class MainPanel {
public:
Test mTest;
MainPanel(Test *test) : mTest(*test) {
cout << "ctor main" << endl;
}
~MainPanel() {
cout << "dctor main" << endl;
}
};
Test Crea() {
cout << "crea" << endl;
return Test();
}
int main()
{
cout << "init " << endl;
MainPanel mainPanel = MainPanel(&Crea());
cout << mainPanel.mTest.mA << endl;
cout << "end " << endl;
}
但是(例如此处有g++
)它拒绝此代码:error: taking address of temporary [-fpermissive]
相反,msvc
似乎permitted。
为什么首先阻止它会“危险”?