复制构造函数知识
copy constructor knowlege
我读过的关于复制构造函数实现的大多数帖子都认为,您还必须重载赋值运算符。我不明白为什么那是真的。我可以在不进行任何运算符重载的情况下实现复制构造函数,而且它运行良好。你能解释一下我遗漏了什么吗?或者为什么我需要遵守这个协议?
以下是一些基本代码,它正以我所期望的方式工作:
//
// Event.h
// PointerPractice
//
#ifndef PointerPractice_Event_h
#define PointerPractice_Event_h
#include <string>
class Event{
public:
Event();
Event(const Event& source);
~Event();
std::string getName();
void setname(std::string theName);
uint64_t getBeginTime();
void setBeginTime(uint64_t time);
uint64_t getDuration();
void setDuration(uint64_t dur);
private:
std::string name_;
uint64_t time_;
uint64_t duration_;
};
#endif
//
// Event.cpp
// PointerPractice
//
#include <iostream>
#include "Event.h"
Event::Event(){
this->name_ ="";
this->time_ = 0;
this->duration_ = 0;
}
Event::Event(const Event& source){
this->name_ = source.name_;
this->time_ = source.time_;
this->duration_ = source.duration_;
}
Event::~Event(){}
std::string Event::getName(){
return this->name_;
}
void Event::setname(std::string theName){
this->name_ = theName;
}
uint64_t Event::getBeginTime(){
return this->time_;
}
void Event::setBeginTime(uint64_t time){
this->time_ = time;
}
uint64_t Event::getDuration(){
return this->duration_;
}
void Event::setDuration(uint64_t dur){
this->duration_ = dur;
}
// main.cpp
// PointerPractice
//
#include <iostream>
#include <vector>
#include "Event.h"
int main (int argc, const char * argv[])
{
Event *firstPtr = new Event();
firstPtr->setname("DMNB");
firstPtr->setBeginTime(4560000);
firstPtr->setDuration(2000000);
std::cout<<"Test first Event object begin time "<<firstPtr->getBeginTime()<<std::endl;
Event *secPtr = new Event(*firstPtr);
secPtr->setBeginTime(2222222);
std::cout<<"Test first Event object begin time "<<firstPtr->getBeginTime()<<std::endl;
std::cout<<"Test second Event object begin time "<<secPtr->getBeginTime()<<std::endl;
return 0;
}
感谢
赋值运算符不会以任何方式影响复制构造函数,您可以在没有赋值运算符的情况下定义复制构造函数。
但你想吗?需要自定义复制行为的类通常希望该自定义行为同时应用于复制构造和复制赋值。这就是"三条规则"(现为"五条规则")的基本原理。如果有原始指针或其他成员不能默认复制和销毁,那么默认的复制赋值运算符可能也不正确。
当然,如果您不喜欢默认的复制赋值操作符,那么简单地禁用复制赋值操作符是完全合理的,而不是编写一个新的。
在您的特定代码的情况下,您不需要自定义的副本分配运算符,这是正确的。但是您也不需要自定义复制构造函数,因为默认行为已经是您想要的了。事实上,编译器生成的默认复制构造函数比您定义的要好,因为它会复制构造成员,而不是默认构造然后重新赋值。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 了解线程构造函数的基础知识
- 复制构造函数知识