gpt4 book ai didi

C++ vector emplace_back 调用复制构造函数

转载 作者:可可西里 更新时间:2023-11-01 18:19:48 28 4
gpt4 key购买 nike

这是一个演示类(class)。我不希望我的类被复制,所以我删除了复制构造函数。我希望 vector.emplace_back 使用此构造函数“MyClass(Type type)”。但是这些代码不会编译。为什么?

class MyClass
{
public:
typedef enum
{
e1,
e2
} Type;
private:
Type _type;
MyClass(const MyClass& other) = delete; // no copy
public:
MyClass(): _type(e1) {};
MyClass(Type type): _type(type) { /* the constructor I wanted. */ };
};

std::vector<MyClass> list;
list.emplace_back(MyClass::e1);
list.emplace_back(MyClass::e2);

最佳答案

vector 需要复制构造函数,以便它可以在需要增加存储空间时复制元素。

您可以阅读 vector 的文档

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) (until C++17)

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of Erasable, but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the allocator completeness requirements.

一些日志记录可以帮助您了解正在发生的事情

For this code

class MyClass
{
public:
typedef enum
{
e1 = 1,
e2 = 2,
e3 = 3,
} Type;
private:
Type _type;
public:
MyClass(Type type): _type(type) { std::cout << "create " << type << "\n"; };
MyClass(const MyClass& other) { std::cout << "copy " << other._type << "\n"; }
};

int main() {
std::vector<MyClass> list;
list.reserve(2);
list.emplace_back(MyClass::e1);
list.emplace_back(MyClass::e2);
list.emplace_back(MyClass::e3);
}

输出是

create 1
create 2
create 3
copy 1
copy 2

因此您可以 emplace_back 确实使用所需的构造函数来创建元素并在需要增加存储时调用复制构造函数。您可以预先调用具有足够容量的 reserve,以避免调用复制构造函数。


如果出于某种原因你真的不希望它是可复制构造的,你可以使用 std::list 而不是 std::vector 作为 list 实现为链表,不需要移动元素。

http://coliru.stacked-crooked.com/a/16f93cfc6b2fc73c

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

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