-1

consider the following codes:

class class1
{

public:
    class1() : _cancel(false) { }

private:
    bool _cancel;

}

class class2
{

public:
    class1 obj1;
}


class class3
{
    void addClass2(class2 _obj2) {
        this->obj2.push_back(_obj2);
    }
private:
    std::vector<class2> _obj2;
}

And using it to other file

void Init()
{

    class2 object2;
    class3 object3;
    object3.addClass2(object2);
}

the _cancel of class1 here did not initialize to false

but I resolve the problem here by this:

//class3

void addClass2(class2 _obj2) {
    this->_obj2.push_back(std::move(_obj2));
}

I'm confused with the behavior of that. Is there any thing I should know about std::vector::push_back ?

EDIT

Sorry for not bringing my copy of code here. I am not on my own computer 'cause I don't have internet

In the class3 implementation above is wrong. so here's the new one

//class3

class class3
{
public:
    void addClass2(std::vector <class2> _obj) {
        this->_obj = _obj;
    }

}
4

1 回答 1

1

此代码false堆叠弯曲(gcc4.7)上输出

编辑我将 bool 更改为 int; 使用 bool,理论上我们有 50% 的机会随机选择正确的值;使用int,它仍然可以42正确输出。

#include <iostream>
#include <vector>
using namespace std;

class class1 {
public:
    class1() : _cancel(42) { }

    int _cancel;
};

class class2
{
public:
    class1 obj1;
};

class class3 {
public:
    void addClass2(class2 _obj2) {
        this->_obj2.push_back(_obj2);
    }

    std::vector<class2> _obj2;
};

int main() {
    class2 object2;
    class3 object3;
    object3.addClass2(object2);

    cout << object3._obj2[0].obj1._cancel << endl;
}
于 2013-03-01T10:44:22.707 回答