
Originally Posted by
mattc
AFAIK, binding a temporary to a const reference is perfectly legal in C++, I am doing that all the time.
I guess my problem has to do with the infamous "implicit sharing" of Qt data types. I think in this case it is breaking the C++ rules in a very dangerous way.
But did you checked that using non-Qt non-implicit shared class will give you result you expect?
I didn't know so I checked (it is not that hard) and I think that you're wrong.
Check this code:
#include <iostream>
class List
{
public:
List() : head(0) {}
~List();
char operator[](int index) const;
List &prepend(char item);
private:
struct Elem {
char data;
Elem *next;
};
Elem *head;
};
List::~List()
{
for (Elem *e = head; e != 0;) {
Elem *d = e;
e = e->next;
delete d;
}
}
char List::operator[](int index) const
{
Elem *tmp = head;
for (int i = 0; i < index; ++i) {
tmp = tmp->next;
}
return tmp->data;
}
List &List::prepend(char item)
{
Elem *e = new Elem;
e->data = item;
e->next = head;
head = e;
return *this;
}
int main()
{
const List &l = List().prepend('a');
std::cout << l[0] << std::endl;
List s;
const List &t = s.prepend('b');
std::cout << t[0] << std::endl;
return 0;
}
#include <iostream>
class List
{
public:
List() : head(0) {}
~List();
char operator[](int index) const;
List &prepend(char item);
private:
struct Elem {
char data;
Elem *next;
};
Elem *head;
};
List::~List()
{
for (Elem *e = head; e != 0;) {
Elem *d = e;
e = e->next;
delete d;
}
}
char List::operator[](int index) const
{
Elem *tmp = head;
for (int i = 0; i < index; ++i) {
tmp = tmp->next;
}
return tmp->data;
}
List &List::prepend(char item)
{
Elem *e = new Elem;
e->data = item;
e->next = head;
head = e;
return *this;
}
int main()
{
const List &l = List().prepend('a');
std::cout << l[0] << std::endl;
List s;
const List &t = s.prepend('b');
std::cout << t[0] << std::endl;
return 0;
}
To copy to clipboard, switch view to plain text mode
There is no Qt class nor implicit sharing. It is simple list implementation, with prepend() method (the same idea as in append, but in my case prepend was easier to implement). What output you expect?
Bookmarks