2

我的问题与以下模式有关...我想使用以下模式来构造一个昂贵的构造SomeData,然后将其移至UsesData.

所以问题是...

中的指针是否ud.dat.m_ptrs保证仍然有效?

struct BigObject{};
struct SomeData
{
    SomeData() = default;

    SomeData(const SomeData &) = delete;
    SomeData & operator = (const SomeData &) = delete;

    SomeData(SomeData &&) = default;
    SomeData & operator = (SomeData &&) = default;

    std::vector<BigObject> m_data1; // big vector
    std::vector<BigObject> m_data2; // big vector

    // (m_ptrs.size() == m_data1.size() + m_data2.size())
    // points to elements in m_data1 and m_data2...
    std::vector<const BigObject * const> m_ptrs;
};

struct Builder
{
    Builder() = delete;
    Builder(const Builder &) = delete;
    Builder & operator=(const Builder &) = delete;
    Builder(Builder &&) = delete;
    Builder & operator=(Builder &&) = delete;

    Builder(int a)  
    {
        // makes sure BigObject vectors in SomeDate are constructed correctly
        // builds m_ptrs... vector of ptrs to m_data1 and m_data2
    }

    SomeData dat;
};

struct UsesData
{
    UsesData() = delete;
    UsesData(const UsesData &) = delete;
    UsesData & operator=(const UsesData &) = delete;
    UsesData(UsesData &&) = delete;
    UsesData & operator=(UsesData &&) = delete;

    UsesData(Builder && from) : dat{ std::move(from.dat) }
    {}

    const SomeData dat;
};

int main()
{
    UsesData ud{ Builder{ 1 } };
    //...
}
4

1 回答 1

4

指针将保持有效。根据移动构造函数的行为std::vector

在容器移动构造(重载(6))之后,指向 other 的引用、指针和迭代器(除了结束迭代器)仍然有效,但引用现在位于*this. 当前标准通过 §23.2.1[container.requirements.general]/12 中的一揽子声明做出此保证,并且正在考虑通过LWG 2321提供更直接的保证。

这意味着,在被移动之后,指针仍然有效并指向被移动到 new 中的元素std::vector

于 2017-05-16T10:20:33.877 回答