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]); }
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With