In my application I have a list of objects. Since I must have only one instance I've disabled both copy constructor and assignment operator. Moving an object is still allowed. But since I perform various manipulations with the objects I need to store the pointer to one of them. Before I've used pointer for that purpose but I want to use a reference now.
For some reason I cannot reassign reference. The error:
error: overload resolution selected deleted operator '='
candidate function has been explicitly deleted
The sample code that demonstrates the issue:
#include <iostream>
class Item
{
public:
Item() { n = (++Item::counter); }
Item(const Item&& other) { n = std::move(other.n); }
Item(const Item& other) = delete;
Item& operator=(const Item& other) = delete;
int Get() { return n; }
private:
int n;
static int counter;
};
int Item::counter = 0;
int main()
{
Item i1;
Item i2;
Item *p = &i1;
printf("%d\n", p->Get());
p = &i2;
printf("%d\n", p->Get());
Item &r = i1;
printf("%d\n", r.Get());
r = i2; // here I get the error
printf("%d\n", r.Get());
return 0;
}
Ok, I can understand if I get error on something like this:
Item i3 = i2;
i.e. in case of really assignment. But here I just want to store a reference to the object, not to assign or copy it to another one.
So my question is how can I store a reference to an non-copied object avoiding pointers?
Aucun commentaire:
Enregistrer un commentaire