Ошибка assignment of member in read only object

I am working on worm_sim simulater , ubuntu, gcc, codeblocks IDE

traffic_source.h file

class Traffic_source : public Buffer_owner, public Connector, public Addressee{
private:
    static unsigned int id_base;
    unsigned int id;
    unsigned int packet_size;
    unsigned int flit_size;
    double packet_generating_rate;
    int pkt_id;
    traffic_source_state ts_state;
    double* packet_to_destination_rate;
    Traffic_mode traffic_mode;
    int period;                // period for packet generation using trace_file
    ifstream trace_file;
    int trace_file_loop_cnt;   // how many times we have gone over the trace file so far
    bool trace_file_empty;
    ofstream trace_dump;       // trace file to dump out

    typedef struct Message {
        int timestamp;
        unsigned int destination;
        unsigned int size;
    } Message, *pMessage;

    Message pre_fetched_message;
    bool get_next_message(Message & msg);

    unsigned int get_destination_uniform(void) const; 
    unsigned int get_destination_transpose1(void) const;
    unsigned int get_destination_transpose2(void) const;
    unsigned int get_destination_hotspot(void) const;
    unsigned int get_destination_customized(void) const;

    void generate_a_packet(unsigned int dst_id);
    void generate_packets(const Message & rec);

public:
    Traffic_source(Position p, int buf_sz);
    ~Traffic_source();
    bool can_send(void) const;
    bool can_receive(void) const { return false; }
    bool send(void);
    bool receive(class Flit * a_flit) { return false; }
    class Connector * get_receiver(void) const; 

    static void reset_id_base(void) { id_base = 0; }

    void tick(void);

    /* traffic control routines */
    void set_packet_generating_rate(double r);
    void set_packet_to_destination_rate(unsigned int dst_id, double rate);
    double get_packet_to_destination_rate(unsigned int dst_id) const;
    double get_total_packet_injection_rate(void) const;
    int set_trace_file(char * file_name);
    bool has_trace_file(void) { return (trace_file.is_open()); }
    int get_id(void) const { return id; }
};

traffic_source.cpp

Traffic_source::Traffic_source(Position p, int buf_sz) : Buffer_owner(buf_sz), Addressee(p) {
    id = id_base ++;
    packet_generating_rate = param.packet_generating_rate;
    packet_size = param.flits_per_packet;
    flit_size = param.flit_size;
    traffic_mode = param.traffic_mode;
    period = 0;
    packet_to_destination_rate = 0;
    pkt_id = 0;
    ts_state = OFF_

    if (param.dump_traffic_source_trace) {
        char file_name[20];
        sprintf(file_name, "%d.trace", id);
        trace_dump.open(file_name);
        if (!trace_dump.is_open() || !trace_dump.good()) {
            cerr << "Error in opening file " << file_name << " for trace dumping" << endl;
            exit(-1);
        }
        trace_dump << "PERIODt" << param.simulation_length << endl;
        trace_dump << "#Trace file dumped by worm_sim from node " << id << endl;
        trace_dump << "#Folloing lines are with format as:" << endl
                   << "#timestampt" << "destinationt" << "message_size(bits):" << endl;
    }
}

bool Traffic_source::can_send(void) const
{
    int router_id=get_id();
    unsigned int local_availability;

    pRouter a_router= param.network->get_router(router_id);
    local_availability=a_router->get_port_availability(0);
    //cout<<local_availability<<endl;
    if (buffer.is_empty())
        return false;
    if(local_availability <= 0)
    {
        packet_generating_rate = 0; //error: assignment of member ‘Traffic_source::packet_generating_rate’ in read-only object|
        set_packet_generating_rate(0); // error: passing ‘const Traffic_source’ as ‘this’ argument of ‘void Traffic_source::set_packet_generating_rate(double)’ discards qualifiers [-fpermissive]|
        return false;
    }


    // This is somehow trick, we need to verify whether the first flit in the fifo
    // is received right in this clock cycle. If so, we can not send it
    const Flit * first_flit = buffer.peek_flit();
    if (first_flit->arrived_in_this_cycle())
        return false;

    pConnector receiver = get_receiver();

    if (receiver)
        return receiver->can_receive();
    else
        return false;
}

the value packet_generating_rate is not const but when i try to modify it either directly or using the set function it give me errors

packet_generating_rate = 0; //error: assignment of member    
 ‘Traffic_source::packet_generating_rate’ in read-only object|

set_packet_generating_rate(0); // error: passing ‘const Traffic_source’ as ‘this’ argument of ‘void Traffic_source::set_packet_generating_rate(double)’ discards qualifiers [-fpermissive]|

although it is used on other files with no problem, any suggestion plz

IDEONE: http://ideone.com/uSqSq7

#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;

struct node
{
    int value, position;
    bool left, right;
    bool operator < (const node& a) const
    {
        return value < a.value;
    }
};

int main()
{
    int n;
    cin >> n;

    vector < node > a(n);
    set < node > s;

    for (auto &i: a)
    {
        cin >> i.value;
        i.left=i.right=0;
    }

    a[0].position=1;
    s.insert(a[0]);

    for (int i=1; i<n; i++)
    {
        auto it=s.upper_bound(a[i]);
        auto it2=it; --it2;
        if (it==s.begin())
        {
            a[i].position=2*it->position;
            s.insert(a[i]);
            it->left=1;
        }
        else if (it==s.end())
        {
            a[i].position=2*(--it)->position+1;
            s.insert(a[i]);
            it->right=1;
        }
        else
        {
            if (it2->right==0)
            {
                a[i].position=2*it2->position+1;
                s.insert(a[i]);
                it2->right=1;
            }
            else
            {
                a[i].position=2*it->position;
                s.insert(a[i]);
                it->left=1;
            }
        }
    }

    for (auto i: a) cout << i.position << ' ';
}

When I compile this code, I get

error: assignment of member ‘node::right’ in read-only object

I think this has something to do with the const in bool operator <, but I cannot get rid of it as it is necessary to create the set.

hanshenrik's user avatar

hanshenrik

19.4k4 gold badges42 silver badges86 bronze badges

asked Feb 10, 2016 at 12:30

anukul's user avatar

7

Angelika Langer once wrote a piece about this: Are Set Iterators Mutable or Immutable?.

You can solve this by defining the Node members immaterial for the set ordering as mutable:

mutable bool left, right;

(see a building version in ideone.)

Personally, I would consider a design mapping the immutable part to mutable parts using a map.

anukul's user avatar

anukul

1,9221 gold badge19 silver badges36 bronze badges

answered Feb 10, 2016 at 12:50

Ami Tavory's user avatar

Ami TavoryAmi Tavory

74.1k11 gold badges139 silver badges182 bronze badges

0

Problem:

Remember that keys in a std::set are constant. You can’t change a key after it’s inserted into the set. So when you dereference the iterator, it necessarily returns a constant reference.

const node& n = (*it);
n->left = 1; //It will not allow you to change as n is const &.

Solution:

As Ami Tavory answered, you can declare left and right as mutable.

answered Feb 10, 2016 at 13:32

CreativeMind's user avatar

tohtarov_ufa

0 / 0 / 0

Регистрация: 13.01.2015

Сообщений: 137

1

01.06.2015, 06:58. Показов 3412. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Добрый день!
У меня есть класс Delegate, в нем указатель на виджет m_editor
.h файл:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Delegate : public QStyledItemDelegate
{
public:
    Delegate (QObject* parent = 0);
    QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option,
                          const QModelIndex& index) const Q_DECL_OVERRIDE;
 
    void setEditorData(QWidget* editor, const QModelIndex& index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget* editor, QAbstractItemModel* model,
                      const QModelIndex& index) const Q_DECL_OVERRIDE;
 
    void updateEditorGeometry(QWidget* editor,
                              const QStyleOptionViewItem& option, const QModelIndex& index) const Q_DECL_OVERRIDE;
    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
 
private:
    QGraphicsView* m_editor = nullptr;
 
};

функция в .cpp файле

C++ (Qt)
1
2
3
4
5
6
7
QWidget* Delegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/* option */,
const QModelIndex & index ) const
{
    m_editor = new QGraphicsView(parent);
...
}

Почему то выдает ошибку
/home/user/KVideoClient/delegate.cpp:18: error: assignment of member ‘Delegate::m_editor’ in read-only object
m_editor = new QGraphicsView(parent);

что для меня лично не понятно

Спасибо за помощь!



0



1443 / 1326 / 131

Регистрация: 20.03.2009

Сообщений: 4,689

Записей в блоге: 11

01.06.2015, 07:52

2

не зная броду, не суйся в воду
Delegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex & index ) const вот эта хрень для чего тут?



0



0 / 0 / 0

Регистрация: 13.01.2015

Сообщений: 137

01.06.2015, 11:57

 [ТС]

3

для того, что это переопределенная функция и без const она вообще не отрабатывает.
почему не отрабатывает — не знаю.



0



1443 / 1326 / 131

Регистрация: 20.03.2009

Сообщений: 4,689

Записей в блоге: 11

01.06.2015, 17:37

4



0



Псевдослучайный

1946 / 1145 / 98

Регистрация: 13.09.2011

Сообщений: 3,215

01.06.2015, 18:00

5

Лучший ответ Сообщение было отмечено tohtarov_ufa как решение

Решение

Цитата
Сообщение от tohtarov_ufa
Посмотреть сообщение

для того, что это переопределенная функция и без const она вообще не отрабатывает.

Ну ещё бы, ведь это будет уже совсем другой метод, а не перегрузка нужного.
createEditor() своей по логике ничего не должна менять в данных делегата, ибо тот только описывает интерфейс взаимодействия с моделями и один экземпляр может одновременно отвечать даже не только за разные записи в одной модели, но и за разные модели вообще.



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

01.06.2015, 18:00

5

b’

bool Traffic_source::can_send(void) constn

n

As others have already pointed out, the problem is that inside a const function (last const in the line) you cannot modify the members of the object. Effectively the member function is translated into something similar to: bool Traffic_source__can_send( const Traffic_source* this, void ), there the this argument is a pointer to const. Which in turn means that packet_generating_rate is const in the context of the function.

n

There are three alternatives that you can follow here:

n

    n

  • dont modify the member
  • n

  • dont mark the function const
  • n

  • make packet_generating_rate mutable
  • n

n

The first two options are the common ones: either the function is const and does not modify the object, or it is not const and can modify the object. There are cases however, where you want to modify a member within a const member pointer. In that case you can mark the member declaration as mutable to enable modification inside const member functions.

n

Note however that in general this is done when the member variable does not take part on the visible state of the object. For example a mutex variable does not change the value returned from a getter or the state of the object afterwards, but getters need to lock (modify) the object to obtain a consistent view of the object in multithreaded environments. The second typical example is a cache, where an object may offer an operation that is expensive to calculate, so the function performing that operation might cache the result for later. Again, whether the value is recalculated or retrieved from the cache it will be the same, so the visible state of the object does not change. Finally, sometimes you might need to abuse the construct to conform to an existing interface.

n

Now it is up to you to determine which of the three options to apply to your design. If you need to modify the member attribute, then either the member is part of the visible state and the function should not be const, or else it is not part of the state of the object and can be marked mutable.

b’

packet_generating_rate = 0;n

n

It is used inside a constant function. In constant function, you cannot change the value of any data member of the object, on which the function was called.

c++ – Error in assignment of member in read-only object

b’

bool Traffic_source::can_send(void) constn

n

this declarations turns this into a pointer to a const. Marking a method as const makes the instance immutable, so you cant modify its members.

n

Why did you mark it as const in the first place, if youre going to modify members?

n

Also, to me it seems that can_send has getter semantics, so logically it shouldnt modify members (I think the error here is that you attempt to modify packet_generating_rate, not making the method const.

Comments

@UralZima

UralZima

referenced
this issue

Sep 27, 2018

@behlendorf

When zfs_kobj_init() is called with an attr_cnt of 0 only the
kobj->zko_default_attrs is allocated.  It subsequently won't
get freed in zfs_kobj_release since the free is wrapped in
a kobj->zko_attr_count != 0 conditional.

Split the block in zfs_kobj_release() to make sure the
kobj->zko_default_attrs are freed in this case.

Additionally, fix a minor spelling mistake and typo in
zfs_kobj_init() which could also cause a leak but in practice
is almost certain not to fail.

Reviewed-by: Richard Elling <Richard.Elling@RichardElling.com>
Reviewed-by: Tim Chase <tim@chase2k.com>
Reviewed-by: John Gallagher <john.gallagher@delphix.com>
Reviewed-by: Don Brady <don.brady@delphix.com>
Reviewed-by: George Melikov <mail@gmelikov.ru>
Signed-off-by: Brian Behlendorf <behlendorf1@llnl.gov>
Closes #7957

@openzfs
openzfs

locked as too heated and limited conversation to collaborators

Jan 28, 2019

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка asilog txt
  • Ошибка ash на приставке цифрового телевидения что делать
  • Ошибка asf passat b6
  • Ошибка ascii android studio

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии