如何限制在堆上分配的对象? [英] How to restrict an object being allocated on the heap?

查看:100
本文介绍了如何限制在堆上分配的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止堆上分配对象?

对于班级CCard,我要阻止用户执行此操作

CCard * ptrCard =新的CPrintCard;

并且只允许他们这样做:

CCard objCard;

我该如何实现呢?

How, I can prevent an object from being allocated on the heap?

For a class CCard i want to prevent users from doing this

CCard *ptrCard = new CPrintCard;

and only allow them to do this:

CCard objCard;

How can i implement this?

推荐答案

在这里回答.简短的版本是坏主意(tm)".正确的文档编制是最好的方法,此链接中显示了一些技巧.

http://stackoverflow.com/questions/10985/如何在堆上创建对象 [
Answered here. The short version is that it''s a "Bad Idea (tm)". Proper documentation is the best way, bsome techniques are shown in this link.

http://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap[^]

BTW, I found this with google, and the link above was the 2nd of 166,000.
.


一种方法可以是声明
One way can be declaring a
private:
  operator new(size_t);


在课堂里.无需实现.

new yourclass这样的表达式并不会编译,因为已声明了类new运算符,但它不能被调用,因为它是私有的.

这类似于声明复制并指定为私有以禁用默认情况下产生的复制和分配功能.


in the class. No implementation is needed.

Simply an expression like new yourclass dosn''t compile since a class new operator is declared but cannot be called, being private.

This is similar as declaring copy and assign as private to disable copy and assignment capabilities produced by default.


此组合:
template <typename T>
class OnStackType
{
  T m_value;

public:
  OnStackType()                   { m_value = T(); };
  OnStackType(const T& init)  { m_value = init; };
  
  operator T&()               { return m_value; };
  T* operator &()             { return &m_value; };
  T& GetValue()               { return m_value; };
};

class A
{
  int m_iMember;

protected:
  A() : m_iMember(0) {};
  A(const A& a) : m_iMember(a.m_iMember) {};
  ~A() {};

public:
  void SetMember(int iSet) { m_iMember = iSet; };

  friend class OnStackType<A>;
};


-将允许代码:OnStacType<A> a;
不是:A a;
但是:OnStackType<A>* pa = new OnStackType<A>(); ...:)


- will allow the code: OnStacType<A> a; ,
not: A a; ,
but: OnStackType<A>* pa = new OnStackType<A>(); ... :)


这篇关于如何限制在堆上分配的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆