【问题标题】:Deep copy dynamically allocated object in C++在 C++ 中深拷贝动态分配的对象
【发布时间】:2014-12-19 09:44:34
【问题描述】:

大家好,我找不到为动态分配的对象构建合适的复制构造函数的方法。它大喊:error: no matching function for call to 'Person::(Person*&')

我的测试代码是这样的:

#include <iostream>
#include <cstring>

class Person
{
private:
    int* age;
    std::string name;
public:
    Person(std::string name_in, int age_in);
    Person(const Person& other);
    ~Person();
    void printAge();
    void printName();
};

Person::Person(std::string name_in, int age_in)
{
    std::cout << "Creating person named " << name_in << std::endl;
    name = name_in;
    age = new int;
    *age = age_in;
}
Person::Person(const Person& other)
{
    std::cout << "Copying person." << std::endl;
    age = new int;
    *age = *other.age;
    name = other.name;
}
Person::~Person()
{
    std::cout << "Freeing memory!" << std::endl;
    delete age;
}

void Person::printAge()
{
    std::cout << "The age is " << *age << std::endl;
}

void Person::printName()
{
    std::cout << "The name is " << name << std::endl;
}


int main()
{
    Person* person1 = new Person("Ramon", 19);
    person1->printAge();
    person1->printName();

    Person* person2 = new Person(person1);
    person2->printAge();
    person2->printName();

    delete person1;
    delete person2;

    return 0;
}

似乎在创建 person2 对象时它只是指向 person1 的指针,但事实并非如此!我声明它是一个新的动态分配对象:Person* person1 = new Person("Ramon", 19);。知道这可能是什么原因吗?

谢谢。

【问题讨论】:

  • 为什么要动态分配年龄?复制构造函数需要一个引用,而不是一个指针,所以你需要Person(*person1)。你的赋值运算符呢?但是,如果您没有使用年龄指针,则不需要任何自定义复制构造函数,并且它会很好地复制。您不需要在此代码中添加任何新内容或删除内容。
  • Person* person2 = new Person(* /* &lt;&lt;&lt; dereference */ person1);
  • @NeilKirk 是的,你是对的,但我正在开发一个更大规模的程序,需要将我的问题转化为一个简单的版本,而且我很糟糕创建明智的例子,你可以看到哈哈我将尝试传递引用而不是指针。谢谢。
  • 哦,是的,你是对的!我需要通过引用传递才能复制。抱歉,我不知道。
  • 非常感谢。你为什么不回答 StackOverflow 的答案?那就不能选你的了。

标签: c++ memory dynamic allocation


【解决方案1】:

复制构造函数通过引用而不是指针获取输入参数。

改变这个:

Person* person2 = new Person(person1);

到这里:

Person* person2 = new Person(*person1);

【讨论】:

    【解决方案2】:

    请务必编写自己的赋值运算符。它类似于复制构造函数,但除了内容的深层复制之外,它还返回对调用对象的引用。

    【讨论】:

      【解决方案3】:

      已经定义的拷贝构造函数是

      Person(const Person& other)

      此方法签名接受对 person 对象的引用,因此您需要发送一个引用。

      在您发送 person1 的代码中,它是由 new 运算符 分配的指针。

      如果你想从另一个对象的指针复制一个对象,那么你应该做一个这样的方法。

      Person::Person(const Person *other)
      {
          std::cout << "Copying person." << std::endl;
          age = new int;
          *age = *other->age;
          name = other->name;
      }
      

      但这不是复制构造函数通常具有的方法签名,在这种情况下不会复制

      人 p2 = person1;

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 1970-01-01
        • 2015-09-14
        • 1970-01-01
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多