Originally Posted by
mattc
AFAIK, binding a temporary to a const reference is perfectly legal in C++, I am doing that all the time.
It is really easier to make a test than to ponder about things one "thinks" he knows. And so I made a test...
Here is our test subject:
#include <QtDebug>
class TestSubject {
public:
TestSubject() {
qDebug() << Q_FUNC_INFO;
}
~TestSubject() {
qDebug() << Q_FUNC_INFO;
}
TestSubject& operator=(const TestSubject &other) {
qDebug() << Q_FUNC_INFO;
return *this;
}
TestSubject(const TestSubject &other) {
qDebug() << Q_FUNC_INFO;
}
};
#include <QtDebug>
class TestSubject {
public:
TestSubject() {
qDebug() << Q_FUNC_INFO;
}
~TestSubject() {
qDebug() << Q_FUNC_INFO;
}
TestSubject& operator=(const TestSubject &other) {
qDebug() << Q_FUNC_INFO;
return *this;
}
TestSubject(const TestSubject &other) {
qDebug() << Q_FUNC_INFO;
}
};
To copy to clipboard, switch view to plain text mode
Here is our test:
const TestSubject &testFun() {
return TestSubject();
}
int main() {
const TestSubject &obj = testFun();
qDebug() << "After testFun call";
return 0;
}
const TestSubject &testFun() {
return TestSubject();
}
int main() {
const TestSubject &obj = testFun();
qDebug() << "After testFun call";
return 0;
}
To copy to clipboard, switch view to plain text mode
Here is the compilation log on gcc:
Originally Posted by
log
main.cpp: In function ‘const TestSubject& testFun()’:
main.cpp:20: warning: returning reference to temporary
And here is the output:
TestSubject::TestSubject()
TestSubject::~TestSubject()
After testFun call
TestSubject::TestSubject()
TestSubject::~TestSubject()
After testFun call
To copy to clipboard, switch view to plain text mode
meaning that there is no copy upon returning a const reference hence when the temporary object is deleted (which happens before the qDebug() line in main()) the const reference points to an invalid object. Regardless if you use implicit sharing or not as it has completely nothing to do with the situation.
Conclusion: binding a temporary to a const reference is not legal in C++.
Bookmarks