在函数内 malloc 全局变量是错误的吗?

发布于 2024-11-30 16:29:33 字数 558 浏览 0 评论 0原文

我有两个 C++ 的“简单”问题。

1-我想创建一个由类中的某些方法共享的变量,所以我所做的就是在头文件中声明该变量并使其成为该类的全局变量。因此,所有方法都可以访问它。这是正确的做法吗?

2-按照我的第一点,如果我在标头中将变量 N 声明为 double *N 。然后在我的一个方法中,我知道

N = (double*) malloc (sizeof(double)*50);

N 将在函数内部进行内存分配。我的问题是:这个内存是只在函数内部保留还是一直保留在全局 N 中?

如果不为 N 保留内存,那么此方法就不是一个好方法,因为系统可能会在稍后的程序过程中覆盖 N 的值。

请提出建议,谢谢

编辑:感谢大家的意见和编辑我的问题。显然我错误地将我的变量称为全局变量,而它实际上是一个类成员。我认为这个声明被称为全局的,因为该变量对于类内的方法是全局的。希望下次我能问一个“更聪明”的问题:)

I have two 'simple' questions in C++.

1- I want to make a variable shared by some methods in a class, so what i am doing is declaring the variable in the header file and make it global to the class. Hence, all methods will have access to it. Is this the right way of doing it ?

2- Following my first point, if i declare variable N as double *N in the header. Then inside one of my methods, i do

N = (double*) malloc (sizeof(double)*50);

I know that N will have a memory allocation inside the function. My question is: is this memory reserved only inside the function or it stays for the global N all the time ?

If the memory won't be reserved for N, then this method wouldn't be a good method, as the system might overwrite the values of N later during the program.

Please kindly advice, Thank you

EDIT: Thank you all for the input and for editing my question. Apparently i mistakenly called my variable as global while it is actually a class member. I thought this declaration is called global since the variable is global for the methods inside the class. Hope i ask a 'smarter' question next time :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

昔梦 2024-12-07 16:29:33
  1. 不,避免全局变量。为您的变量找到正确的范围和封装。把它放在那里。

  2. 如果您将某些内容声明为 double 并尝试为其分配指针,则不会发生任何事情。你的代码根本无法编译。我假设您正在谈论全局double*。您需要为该指针malloc 内存,并且与通常的malloc 一样,它不会在作用域末尾free 释放。您需要自己执行此操作,但这对于全局来说可能不太重要。

我就停在这里。有这么多错误。您不应该在 C++ 中使用 malloc。您不应该在 C++ 中使用普通数组。并且您应该尽可能避免使用全局变量。你应该用代码来说明你想要做什么。

  1. No, avoid globals. Find the right scope and encapsulation for your variable. Put it there.

  2. If you declare something as double and try to assign a pointer to it, nothing is going to happen. Your code is simply not going to compile. I assume you are talking about a global double*. You'd need to malloc memory for this pointer and it is, as usual with malloc not freed at the end of scope. You need to do it yourself but this is probably less important for a global.

I'll just stop here. There is so much wrong. You shouldn't use malloc in C++. You shouldn't use plain arrays in C++. And you should avoid globals as much as possible have globals. You should rather state what you are trying to do, with code.

别忘他 2024-12-07 16:29:33

malloc 的内存将保持有效,直到您释放它。然而,这是一个极其糟糕的设计。从技术上讲,这是合法且正确的。然而,这绝对不是正确的做法。首先,全局变量是不好的。如果您有一个设计并且其中包含全局变量,请再考虑一下,直到它不包含为止。其次,您应该使用newdelete和智能指针,而不是mallocfree。第三,就让它成为类的成员变量吧?

malloc's memory will remain valid until you free it. However, this is a hideously bad design. Technically, this is legal and correct. It is, however, definitely not the right way to do it. First, global variables are bad. If you have a design and it includes a global variable, think again until it doesn't. Second, you should use new, delete and a smart pointer, not malloc and free. Thirdly, just make it a member variable of the class?

走野 2024-12-07 16:29:33

作为一般规则,您应该避免全局变量,除非绝对没有其他解决方案可用(恕我直言,如果软件设计良好,则不应该出现这种情况)。

  1. 如果全球你指的是会员,就像这样

    A级
    {
    私人的:
    双N;
    };

那么是的。

如果 global 你的意思是这样的(据我所知,这是 global 变量的正确概念)

double N;
class A
{
};

,那么你应该避免这种情况并使用前面的(使用变量作为类 >成员)。

  1. 你的例子没有意义,因为 double 已经有一个大小。您需要在 malloc() 中使用指针,例如 double N*。另外,由于您正在使用 C++ 进行编程,因此请使用 new 来代替。由new(推荐)或malloc()(不推荐)分配的所有内存都将保留,除非您手动释放它(当该内存被释放时,您不应该忘记这样做)不再需要)。

As a general rule, you should avoid global variables unless absolutely no other solution is available (which IMHO shouldn't be the case ever if a software is well designed).

  1. If by global you mean as member, like this

    class A
    {
    private:
    double N;
    };

then yes.

If by global you mean something like this (which AFAIK is correct concept for global variable)

double N;
class A
{
};

then you should avoid this and use the previous (use the variable as a class member).

  1. Your example makes no sense since double already has a size. You need to use a pointer with malloc(), for example double N*. Also since you're programming on C++, use new instead. All memory allocated by either new (recommended) or malloc() (not recommended) stays reserved unless you manually free it (which you should not forget to do when that memory is no longer needed).
难以启齿的温柔 2024-12-07 16:29:33

让我们把事情弄清楚一点。假设这是在头文件 members.h 中:

extern double a;     // this is a "global" variable declaration. It needs a definition.

class B {
  double c;          // this is a data member. There will be one in each object of class B
  static double * d; // this is a static data member. There will be a single one for
                     // all objects of class B. It needs a definition.
public:
  void f() { c = 1.0; a = 3.0; }           // A member function can access both static and
                                           // plain data members, as well as globals.
  static void g() { d = new double(2.0); } // A static member function can only access
                                           // static data members and globals.
};

请注意,像 ac 这样的变量/数据成员不需要显式分配。另一方面,d 确实如此,因为它是一个指针。另请注意,在 C++ 中,您使用 new() 而不是 malloc()

这是源文件members.cpp

#include "members.h"

double a; // Definition of global a

double * B::d;  // Definition for static member d

B b1;     // Static instance of class B

int main() {
  B b2;      // Local instance of class B
  b1.f();    // Calling member function f() on b1
  b2.f();    // Calling member function f() on b2
  B::g();    // Calling static member function g()
}

我希望我已经说得足够清楚并消除了您的疑虑。

Let's clear things up a bit. Assuming this is in header members.h:

extern double a;     // this is a "global" variable declaration. It needs a definition.

class B {
  double c;          // this is a data member. There will be one in each object of class B
  static double * d; // this is a static data member. There will be a single one for
                     // all objects of class B. It needs a definition.
public:
  void f() { c = 1.0; a = 3.0; }           // A member function can access both static and
                                           // plain data members, as well as globals.
  static void g() { d = new double(2.0); } // A static member function can only access
                                           // static data members and globals.
};

Note that variables/data members like a or c do not require explicit allocation. On the other hand d does, because it is a pointer. Note also that in C++ you use new() rather than malloc().

This is source file members.cpp:

#include "members.h"

double a; // Definition of global a

double * B::d;  // Definition for static member d

B b1;     // Static instance of class B

int main() {
  B b2;      // Local instance of class B
  b1.f();    // Calling member function f() on b1
  b2.f();    // Calling member function f() on b2
  B::g();    // Calling static member function g()
}

I hope I've been clear enough and covered your doubts.

眼眸里的快感 2024-12-07 16:29:33

根据我作为程序员的经验,我从未在头文件中实例化变量。
相反,我可以在 C 文件中实例化该变量,但在 EXTERN(在头文件中)以便其他类可以使用它。但如果你想声明的话,应该没问题。

当你 malloc 时,你说的是 N 有这个大小。
但是,如果您没有 malloc 它并且尝试在不同的方法中使用它,那么您将遇到分段错误,因为没有为它分配空间(这仅适用于指针和列表,数组和等等,您不需要对单一数据类型执行此操作。)

N 可以在任何地方实例化,但必须在使用之前实例化。

from my experience as a programmer, I never instantiate a variable in a header file.
Rather, I can instantiate the variable in a C file, but EXTERN (in the header file) so that other classes can use it. But if you want to declare it, it should be fine.

And when you malloc you are saying N has this size.
But if you haven't malloc it and you are trying to use it within a different method, then you will have a segmentation fault due to the fact that there is no allocated space for it (this is only for pointers and lists,arrays and etc. you dont need to do it for single data types.)

N can be instantiated anywhere, but it has to be instantiated before used.

你穿错了嫁妆 2024-12-07 16:29:33
  1. 是的,这是正确的方法。
  2. 如果要使用动态分配的内存,则应将 N 声明为“double *”而不是“double”。此外,在 C++ 中使用“new”而不是“malloc”。虽然您还没有使用“delete”释放 N bu ,但它将是全局可用的,因此它保持全局状态,而不是在函数的范围内。
  1. Yes, that is the right way.
  2. If you are going to use dynamically allocated memory, you should declare N as "double *" not "double". In addition, use "new" instead of "malloc" in C++. While you have not released N bu using "delete", it will be globally available, so it stays global, not in the scope of the function.
顾冷 2024-12-07 16:29:33

这不是在 C++ 中构造和管理类的数据成员的惯用方法!通常,您可以按如下方式声明一个对象:

class foo
{
public:
  foo() : N(0.) {}  // initialize N in the ctor
  // interface
private:
  // data
  double N;
};

现在,foo 中的所有方法都可以读取/修改(取决于 constness)成员 N。您无需手动管理 N 的存储,它作为 foo 实例的一部分进行管理。您不需要单独的“全局”变量,除非您希望 foo所有实例及其成员使用相同的 N。即使如此,它是动态的也是没有意义的。

This is not the idiomatic way to construct and manage data members of classes in C++! Typically you would declare an object as follows:

class foo
{
public:
  foo() : N(0.) {}  // initialize N in the ctor
  // interface
private:
  // data
  double N;
};

Now all methods in foo can read/modify (depending on constness) the member N. You don't need to manually manage the storage for N, it is managed as part of the instance of foo. You don't need a separate "global" variable unless you want all instances of foo and it's members to use the same N. Even then, it doesn't make sense for it to be dynamic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文