I have a pair member data in a class: pair<double,double> memory;
How can I change the firs or second element?
If I simply write memory.first = 42 the compiler says read-only structure
If I use memory = pair<double,double>(42,42) than: error passing 'this' argument
I dont understand, please help me

Dani AI

Generated

The two compiler messages you quoted point to the same root cause: the pair object is being treated as const when you try to modify it. That is exactly what was hinting at — a trailing const on the member function (or the instance being const) makes this a pointer-to-const, so assignments like memory.first = ... or memory = std::pair<...>(...) are rejected by the compiler.

A minimal illustration of the problem and two safe fixes:

class Foo {
  std::pair<double,double> memory;
public:
  void update() const {         // <-- this const makes 'memory' read-only here
    memory.first = 1.0;         // compile error: assignment to member of read-only object
  }
};

Fixes:

  • Remove the const qualifier from the member function if the function logically modifies object state.
  • If the function must remain const (for example, it only mutates a cache), declare the member mutable:
    mutable std::pair<double,double> memory;
    void update() const { memory.first = 1.0; }

Quick checklist to debug the original error:

  • Search method prototypes for a trailing const.
  • Check whether the object was created as const.
  • Confirm the member itself is not declared const.
    Avoid const_cast as a routine fix. Use mutable only when the modification does not change the observable logical state (caching, lazy init, bookkeeping).

Recommended Answers

All 2 Replies

duplicate post :(

can you post the function prototype/short segment of code?
Your first example should work, as I compiled the following:

pair<double, double> memory;
	memory.first = 23;
	memory.second = 2;

	cout << memory.first << endl;

however, its possible memory is a class variable and this is a const function, for example, which might cause your errors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.