M
M
Maxim Ivanov2016-05-28 19:25:05
C++ / C#
Maxim Ivanov, 2016-05-28 19:25:05

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;
}

How to make it so that it was impossible to assign a and b. Assignment overloading in a private section does not help, it will only work when we assign *a = *b by value, and then the compiler will warn about such an error.
1e31dc5525d04f3b8e0524fb4e18301c.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#algooptimize #bottize, 2016-05-28
@splincodewd

e.g. unique_ptr , at the moment there might be a better alternative

A
Alexander Movchan, 2016-05-28
@Alexander1705

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;
}

PS operator= must return a reference to the left operand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question