【问题标题】:C++ strange behaviour mutator vectorC++ 奇怪的行为突变向量
【发布时间】:2014-04-08 23:30:46
【问题描述】:

我一直在为学校工作,我们必须创建一个带有 4 个字符串、4 个 int 和一个 vector(int) 作为最后一个参数的 Client 类。问题是,当我想打印所有向量的元素时,如果我直接使用我的 mutator,它会打印废话。

vector<int> v_int;
vector<int>::iterator it_v_i;
v_int.push_back(2);
v_int.push_back(3);
v_int.push_back(7);
v_int.push_back(1);

Client client("nom1", "prenom1", "adress1", "city1", "comment1", 1240967102, 44522, 5, 10, v_int);

v_int = client.getIdResources();
for (it_v_i = v_int.begin(); it_v_i != v_int.end(); it_v_i++) {
    cout << *it_v_i << ", ";
}

按预期打印2,3,7,1,但是下面的代码

for (it_v_i = client.getIdResources().begin(); it_v_i != client.getIdResources().end(); it_v_i++) {
    cout << *it_v_i << ", ";
}

打印不明号码(如 3417664...),不明号码,7, 1

我真的不明白为什么会这样

编辑:

构造函数:

Client::Client(const string& name, const string& surname, const string& adress, const string& city, const string& comment,
            const int& phoneNb, const int& postalCode, const int& termAppointment, const int& priority, const vector<int>& idResources)
                : name(name), surname(surname), adress(adress), city(city), comment(comment), phoneNumber(phoneNb),
                postalCode(postalCode), termAppointment(termAppointment), priority(priority), idResources(idResources)

{ }

突变体:

std::vector<int> getIdResources() const{ return idResources; }

【问题讨论】:

    标签: c++ vector mutators


    【解决方案1】:

    问题是在第二个 sn-p two 临时 vectors 被用于获取 begin()end() 迭代器(假设声明是 std::vector&lt;int&gt; client.getIdResources() 而不是 @ 987654325@)。这意味着it_v_i 指的是被破坏的std::vector 的元素。当 it_v_i 被取消引用时,它会导致未定义的行为。

    为了使第二个代码 sn-p 函数正确,std::vector 的引用需要由 client.getIdResources() 返回。但是,返回对内部类成员的引用会带来其他问题,例如生命周期问题。

    【讨论】:

    • 所以这意味着第一种情况是唯一正确的方法?
    • @DadEapPurple,是或修改getIdResources() 以返回const std::vector&lt;int&gt;&amp;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2016-06-28
    • 2021-10-27
    • 2014-06-05
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多