且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Singleton类,用于将堆移动到堆栈

更新时间:2023-02-25 20:14:36

不,这完全是胡说八道.

No it's utter nonsense.

首先,这些代码甚至都没有使用堆栈(只要我们说的是执行堆栈),并且您显然会误解了Singleton设计模式.

First of all this code doesn't even use the stack (as long as we are speaking of the execution stack), and you clearly misunderstood the Singleton desing pattern.

当您的程序中只需要单个实例,但又想授予对该实例所有功能的访问权限时,可以使用Singleton.它就像一个全局变量,但是您可以限制访问.

You use Singleton, when you only need a single instance in your program, but you want to grant access to all functions to that single instance. Its like a global variable, but you can restrict the access.

第二,如果您需要在C ++中使用强制转换,例如:

Second, if you need to use casting in C++ like:

tmp = (double*)CStack::Instance() -> getAlloc(4*sizeof(double));

您显然错了.现在不要在C ++中使用void*.当您变得更好时,您可以稍后使用它,而不是现在.

You've clearly gone wrong. Don't use void* in C++ for now. You can use it later, when you've gotten better, not for now.

主要问题为什么不将变量移至堆栈?如果您只是想动态分配,为什么还要将其限制在范围内,请使用智能指针,例如std :: auto_ptr.

The main question WHY do you wan't to move variables to the stack? if you simply want to allocate dynamicly, why still limiting it to the scope, use smart pointers, like std::auto_ptr.

如果要创建堆栈,并使用该堆栈存储双打,则可以编写:

if you want to create a stack, and use that to store your doubles you can write:

#include <vector>

int foo()
{
  std::vector<double> stack;

  // push values on the stack
  stack.push_back(1.1);
  stack.push_back(1.2);
  stack.push_back(1.3);

  // remove values from the stack
  stack.pop_back();
  stack.pop_back();
  stack.pop_back();
}