How to prevent copying of pointers?

#include <iostream>
using namespace std;


class Number {

 float* val;
 void operator = (const Number&); // not helping

public:

 Number(float arg){
 val = new float(arg);
}

 float& get(){
 return *val;
}

~Number(){
 delete val;
}
};

int main(int argc, char *argv[]){

 Number* a = new Number(1);
 Number* b = new Number(2);

 a = b; // memory leak
 // a will point to b
 // now we don't know the link to the area a



 cout << a->get() << endl;
 cout << b->get() << endl;

 cout << a->get() / b->get() << endl;

 delete a;
 delete b; // invalid pointer, the program crashes


 return 0;
}</iostream>


How to make so that it was impossible to assign a and b. Overload assignments in the private section doesn't help, it will only work when we are on the value we assign *a = *b then the compiler will warn of this error.

1e31dc5525d04f3b8e0524fb4e18301c.png
July 9th 19 at 10:49
3 answers
July 9th 19 at 10:51
Solution
for example unique_ptr , at the moment perhaps there is a better alternative
but unique_ptr can be implemented? as a code, for example, write? - lon34 commented on July 9th 19 at 10:54
Can
You can open a source file on your computer, if necessary. - mercedes commented on July 9th 19 at 10:57
July 9th 19 at 10:53
Solution
Number* const a = new Number(1);
Number* const b = new Number(2);
but it will be impossible to override in the future, a = new Number(3); - lon34 commented on July 9th 19 at 10:56
July 9th 19 at 10:55
Implement the assignment operator:
// So, if you want to point to one area:
Number& operator = (const Number& other)
{
 delete val;
 this->val = other.val;
 return *this;
}

// So, if must be created a copy of the value:
Number& operator = (const Number& other)
{
 delete val;
 this->val = new float(*(other.val));
 return *this;
}

PS operator= should return a reference to the left operand.
make copies, just overload it so that there are no leaks. - Grace_Kassulke92 commented on July 9th 19 at 11:10
void operator = does not work in our case, tested on your example - lon34 commented on July 9th 19 at 10:58
: what does "not working"? - mercedes commented on July 9th 19 at 11:01
a = b is still copied - lon34 commented on July 9th 19 at 11:04
: and what kind of behavior do you expect? - lon34 commented on July 9th 19 at 11:07
so, a = b could not assign what to do about it? - lon34 commented on July 9th 19 at 11:13
: try this ad: Number& operator=(const Number&) = delete; - Grace_Kassulke92 commented on July 9th 19 at 11:16
look, I've attached a screenshot showing what doesn't work, the compiler, why? I copied your code - Grace_Kassulke92 commented on July 9th 19 at 11:19
Number& operator=(const Number&) = delete;

added, still copies there is a leak, as when you remove, says error - lon34 commented on July 9th 19 at 11:22

Find more questions by tags C++