简体   繁体   English

将矢量元素分配给调用emplace_back的函数的结果?

[英]Assigning a vector element to result of function that invokes emplace_back?

The test method on the following class does not have the effect I would expect it to. 以下类的测试方法没有我期望的效果。 I have a suspicion it is something to do with the fact that the invocation of emplace_back somehow invalidates the reference obtained via the subscript. 我怀疑这与以下事实有关:emplace_back的调用以某种方式使通过下标获得的引用无效。

Either way I would expect the second print in test to result in 无论哪种方式,我都希望测试中的第二张打印结果能够

v[0] = 1

however both result in 但是两者都会导致

v[0] = 5

suggesting that the assignment does not take place. 提示作业没有发生。

class FooBar {
    vector<size_t> v;
public:
    size_t add(size_t x) {
        cout << "add(" << x << ")" << endl;
        size_t K(v.size());
        v.emplace_back(x);
        return K;
    }

    void test(size_t idx) {
        cout << "v[" << idx << "] = " << v[idx] << endl;
        v[idx] = add(0);
        cout << "v[" << idx << "] = " << v[idx]<< endl;
    }
};

int main(int argc, char* argv[])
{       
    FooBar f;
    f.add(5);
    f.test(0);
}

I know that I can get around the problem by creating a temporary to store the result of add and then perform the assignment but I am interested as to why I cannot use just a straight assignment and why I do not get any kind of error when attempting to perform this. 我知道我可以通过创建一个临时存储器来存储add结果然后执行分配来解决该问题,但是我对为什么不能仅使用直接分配以及为什么在尝试时没有得到任何错误感到兴趣执行此操作。

Compiled and tested with MSVC (Visual Studio 2015). 使用MSVC进行编译和测试(Visual Studio 2015)。

The line 线

    v[idx] = add(0);

is cause for undefined behavior. 是导致未定义行为的原因。 You are modifying the contents of v in add while assuming that v[idx] will be valid. 假设v[idx]有效,您正在修改addv的内容。

For predictable behavior, you can use: 对于可预测的行为,可以使用:

void test(size_t idx) {
    cout << "v[" << idx << "] = " << v[idx] << endl;
    size_t val = add(0);
    v[idx] = val;
    cout << "v[" << idx << "] = " << v[idx]<< endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM