资源获取正在初始化-请入门指南

时间:2019-05-16 10:44:28

标签: c++ raii

作为我的软件工程学位的一部分,我们正在研究高级面向对象编程。这是使用C ++作为语言来完成的。该课程是兼职课程,因此所有资料每周压缩为2个小时的讲座。对于C ++来说,它是全新的,学习曲线陡峭。我们目前正在讨论RAII,内存分配和清理的概念对我来说是新的。我们被要求创建一个由int和char *构造的类。

我们被要求为以下内容创建构造函数。

#ifndef __CAT__
#define __CAT__
#include <iostream>

class Cat{

private:
    int lives;
    char* name;

public:
    Cat(int _lives, char* _name);
    Cat(const Cat &rhs);
    Cat& operator=(const Cat &rhs);
    Cat(Cat &&rhs);
    Cat& operator=(Cat &&rhs);
    ~Cat();

    friend std::ostream& operator<<(std::ostream& os, const Cat &rhs);
};
#endif

我设法构建了构造函数,解构函数和Copy构造函数。他们编译并似乎按照他们的预期去做。

Cat::Cat(int _lives, char* _name){
    printf("Constructor called!\n");

    lives = _lives;
    int length = strlen(_name)+1;
    name = new char[length];
    memcpy(name, _name, length*sizeof(char));
}

Cat::~Cat(){
    printf("Deconstructor called!\n");

    if(name != nullptr){
        delete [] name;
        name = nullptr;
    }
    lives = 0;
}

Cat::Cat(const Cat &rhs){
    printf("Copy Constructor called.\n");
    lives = rhs.lives;
    int length = strlen(rhs.name)+1;
    name = new char[length];
    memcpy(name, rhs.name, length*sizeof(char));
}

我需要构建副本分配,移动和移动分配构造函数。

我知道副本分配正在获取一个已经分配的对象,并将该对象的另一个实例复制到这个已经分配的对象。我知道这意味着释放现有对象的资源并分配资源以接受要复制的对象。

移动将对象A移动到新的对象B并取消分配对象A的资源。移动分配相同,但是对象B不是新的,但已经存在。

我需要编写以下构造函数。

Cat& Cat::operator=(const Cat &rhs) {
    printf("Copy Assignment Constructor called.\n");

}

Cat::Cat(Cat &&rhs){
    printf("Move Constructor called.\n");

}

Cat& Cat::operator=(Cat &&rhs){
    printf("Move Assignment Constructor called.");

}

因此它们允许运行以下内容

#include <iostream >
#include "Cat.h"

    // std :: move forces the move constructor to be called ...
    // Otherwise the compiler can optimize ...
    // Cat d = make_cat (); ... into ...
    // Cat d(42 , " Douglas ");
    // without ever invoking the move constructor .
Cat make_cat() {
    Cat tmp(42 , "Douglas");
    return std :: move (tmp);
}


int main (int argc , char* argv[]){
    Cat a(9, "Garfield");
    std::cout << a << std::endl;

    { // Anonymous scope - copy constructor
        Cat b = a;
        std::cout << b << std::endl;
    }

    { // Anonymous scope - copy assignment
        Cat c(666 , "Catbert")
        std::cout << c << std::endl;
        c = a;
        std::cout << c << std::endl;
    }

    { // Anonymous scope - move constructor
        Cat d = make_cat();
        std::cout << d << std::endl;
    }

    { // Anonymous scope - move assignment
        Cat e(9, "Maru");
        std::cout << e << std::endl;
        e = make_cat();
        std::cout << e << std::endl;
    }
    return 0;
}

我只是不太了解C ++才能做到这一点。任何帮助,资源或建议,将不胜感激。

更新 我已经阅读了帖子评论中所有指向信息的链接,并与我的讲师进一步讨论了该问题。现在,我已经通过编写所有构造函数来完成任务。我将在提交截止日期为2019年5月22日之后发布解决方案。

谢谢 保罗。

0 个答案:

没有答案