复制构造函数知识

copy constructor knowlege

本文关键字:知识 构造函数 复制      更新时间:2023-10-16

我读过的关于复制构造函数实现的大多数帖子都认为,您还必须重载赋值运算符。我不明白为什么那是真的。我可以在不进行任何运算符重载的情况下实现复制构造函数,而且它运行良好。你能解释一下我遗漏了什么吗?或者为什么我需要遵守这个协议?

以下是一些基本代码,它正以我所期望的方式工作:

//
//  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;
}

感谢

提供的信息

赋值运算符不会以任何方式影响复制构造函数,您可以在没有赋值运算符的情况下定义复制构造函数。

但你想吗?需要自定义复制行为的类通常希望该自定义行为同时应用于复制构造和复制赋值。这就是"三条规则"(现为"五条规则")的基本原理。如果有原始指针或其他成员不能默认复制和销毁,那么默认的复制赋值运算符可能也不正确。

当然,如果您不喜欢默认的复制赋值操作符,那么简单地禁用复制赋值操作符是完全合理的,而不是编写一个新的。

在您的特定代码的情况下,您不需要自定义的副本分配运算符,这是正确的。但是您也不需要自定义复制构造函数,因为默认行为已经是您想要的了。事实上,编译器生成的默认复制构造函数比您定义的要好,因为它会复制构造成员,而不是默认构造然后重新赋值。