共享指针向量更新push_back上的现有元素

时间:2017-07-08 20:42:49

标签: c++ vector shared-ptr

基本上,我有shared_ptr的向量作为类的成员数据。 通过从另一个类函数调用成员函数来填充此向量 问题添加到向量的新元素会更新现有元素的值。

设置如下:

A类

/*
 * Class A has a header with class declarations and a distinct implementation.
 * For the sake of brevity, the relevant information is shown in this snippet.
 */
class A {
public:
    A(std::string name) : m_name(name);
    std::string& get_name();
private:
    std::string m_name;
}
typedef std::shared_ptr<A> A_ptr;

B类

/*
 * Class B has a header with class declarations and a distinct implementation.
 * For the sake of brevity, the relevant information is shown in this snippet.
 */
class B {
public:
    void add_element(A_ptr& element) {
        /*
         this is where the problem is:
         i DO get the proper element (i can verify this by calling the get_name() method on `element`).

         Assume we got in succession:
         - ONE
         - TWO
         - THREE

         ...
        */
        std::cout << element -> get_name << std::endl;

        m_elements.push_back(element);

        /*
         ...

         fast forward here, when I print the content of the vector held in this class,
         the old elements added have been updated somehow and I get this:

         - when we get ONE, the vector contains: [ONE]
         - when we get TWO on the next call to this function, the vector contains: [TWO, TWO]. I expect [ONE,TWO]
         - when we get THREE on the next call to this function, the vector contains: [THREE, THREE, THREE]. I expect [ONE, TWO, THREE]

         -> WHAT ON EARTH IS GOING ON HERE?
        */
        for (auto it = m_elements.begin(); it != m_elements.end(); ++it)
            std::cout << (* it) -> get_name() << std::endl;
    }
private:
    std::vector<A_ptr> m_elements;
}
typedef std::shared_ptr<B> B_ptr;

class B是问题类。在add_element()函数中,我正在添加要添加的正确元素(即ONETWOTHREE)。
但是,在push_back()之后,不仅添加了新元素,现有元素的值都更新为添加的新元素。
所以说我添加名称为ONE然后TWO的元素,而不是将元素作为[ONE, TWO]获取,我得到[TWO, TWO]

C类

/*
 * Class C has a header with class declarations and a distinct implementation.
 * For the sake of brevity, the relevant information is shown in this snippet.
 */
class C {
public:
    void do_something() {
        std::string name = name_obtained_dynamically();
        B_ptr manager(new B());

        do {
            A_ptr element_one(nullptr);
            A_ptr element_two(nullptr);

            if (we_are_good) {
                element_one.reset(new A(name));
            }
            else {
                element_two.reset(new A(name));
            }

            if (element_one !=nullptr)
                manager -> add_element(element_one);
            else
                manager -> add_element(element_two);
        } while(condition_is_true);
    }
}

class Cadd_element()调用class B并继续向所述向量添加元素 据我所知,问题可能在于我在该循环中使用了共享指针 但究竟我做错了什么,我不知道。

0 个答案:

没有答案