copy-constructor - 复制构造函数被多次调用
问题描述
下面的代码输出:
Default ctor is called
Copy ctor is called
Default ctor is called
Copy ctor is called
Copy ctor is called
为什么每次push_back()
调用复制构造函数都加 1?我认为它应该只调用一次。有什么我想念的吗?请我需要详细的解释。
class A
{
public:
A()
{
std::cout << "Default ctor is called" << std::endl;
}
A(const A& other)
{
if(this != &other)
{
std::cout << "Copy ctor is called" << std::endl;
size_ = other.size_;
delete []p;
p = new int[5];
std::copy(other.p, (other.p)+size_, p);
}
}
int size_;
int* p;
};
int main()
{
std::vector<A> vec;
A a;
a.size_ = 5;
a.p = new int[5] {1,2,3,4,5};
vec.push_back(a);
A b;
b.size_ = 5;
b.p = new int[5] {1,2,3,4,5};
vec.push_back(b);
return 0;
}
解决方案
这是因为push_back
在您的示例中,每次都必须进行重新分配。如果您reserve
提前确定尺寸,那么您只会看到一份副本。
std::vector<A> vec;
vec.reserve(10);
推荐阅读
- javascript - 调用 setState 后 React 如何区分新旧状态?
- wso2 - Wso2 APIM Analytics 2.6.0 数据库连接
- javascript - 我正在尝试制作一个发送图像的 JS 机器人
- symfony - Symfony 5 路由命名参数约束验证器
- javascript - 我是否需要使用 useEffect 重新渲染组件?
- java - 客户端流式传输 GRPC 时如何设置超时?
- mysql - NodeJS MySQL异常超时不是登录问题
- javascript - WebStorm 使用 SourceMaps 调试远程 React Web 应用程序
- c# - 旋转角色时 Cinemachine 的 Unity 问题
- firebase - 如何自动更改调用 firebase 函数的路径