【问题标题】:Deconstruct const pointer?解构 const 指针?
【发布时间】:2018-05-09 14:03:29
【问题描述】:

这可能是非常基本的,但我被卡住了,根本不知道问题出在哪里。

主代码被预定义为一个任务。目标是尽可能多地使用 const。以下构造函数只是应该将文字字符串复制到 const m_data 并且工作正常,但我无法释放内存 - 它总是留下 1 个块。我错过了什么?

main.cpp

#include <iostream>
#include "immstring.hpp"
using namespace std;
using namespace Util;

int main() 
{
  const ImmutableString s1("Hello");
}

immu.hpp

#include <cstring>
namespace Util {
class ImmutableString {
public:
    ImmutableString(const char* src);
    ~ImmutableString();

private:
    char* const m_data;
};
}

immu.cpp

#include "immstring.hpp"
#include <iostream>
#include <cstring>
namespace Util 
{
ImmutableString::ImmutableString(const char* src)
    :m_data{strcpy(new char[strlen(src)+1],src)}{}

ImmutableString::~ImmutableString() 
{
    delete m_data;
}
}

【问题讨论】:

  • delete 你是什么newdelete[] 你是什么new[]
  • 更好的是,avoid new and new[]
  • 请解释你为什么使用new[]然后delete
  • 不确定这与const 有什么关系?
  • 请注意,“仍然可以访问”并不一定意味着存在内存泄漏问题——它可能是故意的。 stackoverflow.com/questions/3840582/…

标签: c++ constructor constants valgrind


【解决方案1】:

要保留所有数组内存块,您必须像这样使用删除:

delete[] m_data;

谢谢, 罗宾。

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 2022-11-23
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    相关资源
    最近更新 更多