小编Joe*_*Joe的帖子

如果在C++中的私有函数中分配内存,是否可以在析构函数中释放内存?

我试图在全局范围中定义一个包含一些动态分配的数组的类.当调用类的构造函数时,程序无法访问通过参数文件读取的用户定义的参数(即模拟中的年数),因此无法将内存分配到适当的大小.我的想法是在类中的私有函数内分配内存,然后使用析构函数释放它.一些示例代码:

class Simulation{
private:
    int initial_call; //a flag used to initialize memory
    double *TransferTracker;
public:
    Simulation();
    ~Simulation();
    void calc();
};

Simulation simulator; //global instance of Simulation

Simulation::Simulation()
{
   initial_call = 1;
}
Simulation::~Simulation()
{
    //when calling the destructor, though, the address is
    //0xcccccccc and the following attempt to delete produces
    //the compiler error.
    delete [] TransferTracker; //see error
}
void Simulation::calc()
{
    for (int i = 0; i < num_its; i++)
    {
         if (initial_call)
         {
             TransferTracker = new double [5]; …
Run Code Online (Sandbox Code Playgroud)

c++ memory constructor destructor

3
推荐指数
1
解决办法
1287
查看次数

我可以创建一个C++"zap"函数,如果它没有分配内存,它可以在指针上运行吗?

我编写了一个zap()函数来解除分配1-d数组,如下所示.

void zap(double *(&data))
{
    if (data != NULL)
    {
       delete [] data;
       data = NULL;
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

我的印象是if data != NULL不会试图释放从未分配过的记忆,但我认为我错了.我有以下实施问题.

void fun()
{
    int condition = 0;
    double *xvec;
    double *yvec;
    allocate_memory_using_new(yvec); //a function that allocates memory
    if (condition == 1) allocate_memory_using_new(xvec);
    //some code
    //deallocate memory:
    zap (yvec);
    zap (xvec); //doesn't work
    return;
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

 Unhandled exception at 0x6b9e57aa (msvcr100d.dll) in IRASC.exe: 0xC0000005: Access
 violation reading location 0xccccccc0.
Run Code Online (Sandbox Code Playgroud)

所以我意识到当显然指针从未被实际使用时,尝试调用zap并不是一件令人向往的事情.我只是想知道是否有办法在zap()函数的某个点检查指针的地址以避免异常.在此先感谢您的帮助和见解!

c++ memory-management

2
推荐指数
1
解决办法
282
查看次数

如何在标准构造函数之外设置boost :: uniform_int_distribution的参数?

我在Boost 1.52中使用uniform_int_distribution使用基本的样板代码生成随机数:

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

boost::random::mt19937 gen;

int roll_die()
{
    boost::random::uniform_int_distribution<> dist(1, 6);
    return dist(gen);
}

int main()
{
    for (int i = 0; i < 10; i++) std::cout << roll_die() << std::endl;     
}
Run Code Online (Sandbox Code Playgroud)

我在一个更大的项目中实现了其中的一部分,并且效果很好。这是我的问题。

在上面的函数中,似乎dist对象是该函数的本地对象。如果您多次调用roll_die(),似乎dist()对于函数而言是本地的,这会带来很多开销。

我认为最好一次设置此对象的min和max参数,然后在更大的对象或其他对象中仅包含dist的一个实例。如何做到这一点?我试图了解类模板的“公共成员函数”部分:http : //www.boost.org/doc/libs/1_47_0/doc/html/boost/random/uniform_int_distribution.html#id744736-bb,但是在我头上。在该文档中,我看到:

void param(const param_type & param); //Sets the parameters of the distribution.
Run Code Online (Sandbox Code Playgroud)

您实际上如何使用它?.param()本身是要调用的函数,还是其他函数的替代者?我找不到另一个能满足我要求的增强示例。预先感谢您的协助和建议!

c++ random constructor boost

0
推荐指数
1
解决办法
2467
查看次数