gpt4 book ai didi

c++ - 函数更改 const 对象

转载 作者:IT老高 更新时间:2023-10-28 21:34:49 26 4
gpt4 key购买 nike

我有接受 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]);
}

最佳答案

仔细考虑vertex.push(vertex[0]);push 函数中的 t 是对 vertex[0] 的常量引用。

但是在 push_back 之后, vector 的内容已经移动(由于内存重新分配),因此 vector[0] 已经移动到别处。 t 现在是一个悬空引用

这是未定义的行为轰隆隆

关于c++ - 函数更改 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com