提问人:Russell Butler 提问时间:1/18/2023 更新时间:1/18/2023 访问量:58
为什么当我使用 Vector 时,push_back的每个元素都会调用 Copy 构造函数?[复制]
why is copy constructor called for every element of vector when i use push_back? [duplicate]
问:
我正在做这个练习,其中我实现了一个包含动态分配的内置数组 (int*) 的类。我正在尝试实现 Big 5,我认为它正在工作(无论如何它都会编译和运行),但是每次我向包含我的类类型对象的向量添加新元素时(参见 main),它似乎都会在向量中的所有元素上调用复制构造函数!(请参阅下面的输出)。
这是 C++ 向量的正常行为,还是我做错了什么?谢谢
class LargeTypeRaw
{
public:
LargeTypeRaw(size_t initialSize = 10)
: data{ new int[size] }, size{ initialSize }
{
std::cout << "normal constructor called" << std::endl;
}
LargeTypeRaw(const LargeTypeRaw& other)
: size{ other.size }, data{ new int[other.size]}
{
std::copy(other.data, other.data + other.size, data);
std::cout << "copy constructor called" << std::endl;
}
LargeTypeRaw(LargeTypeRaw&& other)
: size{ other.size }, data{ other.data }
{
std::cout << "move constructor called" << std::endl;
other.data = nullptr;
}
LargeTypeRaw& operator=(const LargeTypeRaw& other)
{
std::cout << "copy assignment operator called" << std::endl;
if (&other != this)
{
delete[] data;
data = new int[other.size];
std::copy(other.data, other.data+other.size, data);
}
return *this;
}
LargeTypeRaw& operator=(LargeTypeRaw&& other)
{
std::cout << "move assignment operator called" << std::endl;
if (&other != this)
{
delete[] data;
data = other.data;
other.data = nullptr;
}
return *this;
}
~LargeTypeRaw()
{
std::cout << "destructor called " << std::endl;
delete [] data;
}
size_t getSize() const
{
return size;
}
bool operator<(const LargeTypeRaw& rhs) const
{
return size < rhs.size;
}
private:
int* data;
size_t size;
};
int main()
{
//example using LargeTypes that hold int
std::vector<LargeTypeRaw> vec{};
for (int i = 0; i < 5; i++)
{
size_t size = rand() % 10;
std::cout << "initializing another object " << std::endl;
LargeTypeRaw lt{ size };
std::cout << "adding the new object to the vector " << std::endl;
vec.push_back(lt);
}
}
答: 暂无答案
评论
noexcept