【发布时间】:2018-04-05 16:18:01
【问题描述】:
有一个函数可以创建新内存并在构造函数中使用。 但是,我不知道如何在析构函数中访问它来删除它。
在构造函数中使用(相同文件)player.cpp
#include <string.h>
#include "Player.h"
// TODO: Fix the bugs in this file
Player::Player(const char* name) : name_(0)
{
copyString(&name_, name);
}
Player::Player(const Player& copy) : name_(0)
{
name_ = copy.name_;
}
Player::~Player()
{
delete [] name_; // Not sure if it works. errors promts- double free
}
Player& Player::operator=(const Player& copy)
{
return *this;
}
void Player::copyString(char** dest, const char* source)
{
unsigned int str_len = strlen(source);
char* str = new char[str_len+1]; //This line
strncpy(str, source, str_len);
str[str_len] = '\0';
*dest = str;
}
std::ostream& operator<<(std::ostream& out, const Player& player)
{
out << player.name_ << std::endl;
return out;
}
我只能更改 .cpp 文件。 我添加了删除行 i 析构函数,但出现错误。
【问题讨论】:
-
delete [] name_;?您必须发布更多代码,包括您的类定义以获得更明智的答案。 -
如果
name_指向那个内存,你不能delete[] name_;吗?考虑在实际项目中使用std::string,并使用智能指针代替原始的拥有指针。 -
看起来你有(或需要)一个自定义析构函数。一些抬头阅读试图避免接下来的几个错误:What is The Rule of Three?
-
@RetiredNinja 我按照你的建议做了,但出现了错误。 '双重免费'
-
您的赋值运算符和复制构造函数不正确,只是在复制指针。如果您想正确执行此操作,则需要制作数据的副本。 stackoverflow.com/questions/4172722/what-is-the-rule-of-threestackoverflow.com/questions/14063791/…
标签: c++ function memory-leaks constructor new-operator