我有接受const引用作为参数的函数.它不应该改变参数,但它确实(变量"_isVertex").怎么解决这个问题?这是代码:
#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]);
}
Run Code Online (Sandbox Code Playgroud)
Bat*_*eba 32
仔细考虑vertex.push(vertex[0]);.t在函数中push是一个常量引用vertex[0].
但是之后push_back,向量的内容已经移动(由于内存重新分配),因此vector[0]已经转移到其他地方.t现在是一个晃来晃去的参考.
这是未定义的行为.繁荣.