Answer the question
In order to leave comments, you need to log in
How to disable copying of pointers?
#include <iostream>
using namespace std;
class Number {
float* val;
void operator = (const Number&); // не помогает
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; // утечка памяти
// a будет указывать на b
// теперь мы не знаем ссылку на область a
cout << a->get() << endl;
cout << b->get() << endl;
cout << a->get() / b->get() << endl;
delete a;
delete b; // invalid pointer, программа падает
return 0;
}
Answer the question
In order to leave comments, you need to log in
e.g. unique_ptr , at the moment there might be a better alternative
Implement the assignment operator:
// Так, если хотите, чтоб они указывали на одну область:
Number& operator = (const Number& other)
{
delete val;
this->val = other.val;
return *this;
}
// Так, если должна создаваться копия значения:
Number& operator = (const Number& other)
{
delete val;
this->val = new float(*(other.val));
return *this;
}
operator=
must return a reference to the left operand.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question