Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function changes const object

Tags:

I have function which accepts const reference as argument. It should not change argument, but it does (variable "_isVertex"). How can this be fixed? Here is the code:

#include <vector> #include <iostream>  using namespace std;  class Element { public:     bool isVertex() const     { return _isVertex; };  private:     bool _isVertex = true; };  class ElementContainer : public vector <Element> { public:     void push(const Element &t)     {         // here everything is fine         cerr << t.isVertex() << ' ';         push_back(t);         // and here _isVertex is false, should be true!         cerr << t.isVertex() << '\n';     } };  int main() {     ElementContainer vertex;      vertex.push({});     vertex.push(vertex[0]); } 
like image 458
Vsh Fbvsfvs Avatar asked Oct 21 '15 12:10

Vsh Fbvsfvs


People also ask

Why do const objects change?

The property of a const object can be change but it cannot be change to reference to the new object. The values inside the const array can be change, it can add new items to const arrays but it cannot reference to a new array. Re-declaring of a const variable inside different block scope is allowed.

Can const object value change?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

How do you update const objects?

Use dot or bracket notation to update the values of an object that was declared using the const keyword, e.g. obj.name = 'New Value' . The key-value pairs of an object declared using const can be updated directly, but the variable cannot be reassigned.

What kind of functions can a const object invoke?

an object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object. A const object can be created by prefixing the const keyword to the object declaration.


1 Answers

Consider carefully vertex.push(vertex[0]);. t in the function push is a constant reference to vertex[0].

But after the push_back, the contents of the vector have moved (due to a memory reallocation), and therefore vector[0] has moved elsewhere. t is now a dangling reference.

That's undefined behaviour. Boom.

like image 164
Bathsheba Avatar answered Sep 18 '22 16:09

Bathsheba