gpt4 book ai didi

C++ std::deque 复制构造函数问题

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:39 24 4
gpt4 key购买 nike

#include <deque>
#include <vector>

struct A
{
A(int* const p) : m_P(p) {}
A(A&& rhs) : m_P(rhs.m_P) { rhs.m_P = nullptr; }
A& operator=(A&& rhs) { delete m_P; m_P = rhs.m_P; rhs.m_P = nullptr; }
~A() { delete m_P; }

A(A const& rhs) = delete;
A& operator=(A const& rhs) = delete;

int* m_P;
};

int main()
{
#ifdef DDDEQUE
std::vector<std::pair<int, std::deque<A> > > vd;
vd.emplace(vd.end(), 1, std::deque<A>());
#endif // #ifdef DDDEQUE

std::vector<std::pair<int, std::vector<A> > > vv;
vv.emplace(vv.end(), 1, std::vector<A>());
}

如果使用 g++ 4.8.5、5.2.0、5.3.0 和 -DDDDEQUE 进行编译,我会收到一条以

结尾的详细错误消息
.../bits/stl_construct.h:75:7: error: use of deleted function ‘A::A(const A&)’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^
gcc.cpp:11:5: note: declared here
A(A const& rhs) = delete;

没有 -D... 可以编译。用VC2015、VC2012两个版本都编译OK。deque(但不是 vector)是否需要 gcc 的复制构造函数?

最佳答案

这似乎特定于 libstdc++ (gcc);给出下面的代码;

struct A
{
A() {};
A(A&&) noexcept { }
A& operator=(A&&) noexcept { return *this; }
~A() { }
};

int main()
{
std::vector<A> a;
a.push_back(A{}); // or emplace(a.end()... etc.
std::vector<std::deque<A>> b;
b.push_back(std::deque<A>());
std::vector<std::pair<int,A>> c;
c.push_back(std::pair<int,A>{});
std::vector<std::pair<int,std::deque<A>>> d;
d.push_back(std::pair<int,std::deque<A>>{});
}

G++ 无法编译 bd,clang 编译所有 4 个(除了可能的 d 取决于所使用的 libc++ 版本)和MSVC 编译所有 4 种情况(使用它们自己的相关标准库;使用 libstdc++,clang 也无法通过 bd)。

Does deque (but not vector) need the copy constructor for gcc?

看起来,是的,gcc 仍然需要复制构造函数。


用更正式的术语来说;在 C++03 中 std::deque要求容器中使用的类型是Copy ConstructibleCopy Assignable。这在 C++11 中发生了变化,要求放宽了,尽管通常仍然需要完整的类型 - 给定 OP 示例,您的标准库仍然需要复制构造和赋值。

来自链接引用;

T - The type of the elements.

T must meet the requirements of CopyAssignable and CopyConstructible. (until C++11)

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements. (since C++11)

关于C++ std::deque 复制构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38912346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com