如何仅在1>堆栈上创建对象而不在堆上创建对象,2>堆只在堆栈上不创建

时间:2016-03-18 06:45:10

标签: c++ object

仅在堆上创建对象 - > 1>代码

有什么问题
class B 
{ 
~B(){}  
public: 
void Destroy() 
{ 

delete this; 
} 

}; 

int main() { 
B* b = new B(); 
b->Destroy(); 

return 0; 
} 

为什么你不能在堆栈上创建类b的对象 2 - ;

class B
{
    B(){}   
    public:
    static B* Create()
    {

        return new B();
    }

};

int main() {
    //B S;
    B* b = B::Create();

    return 0;
}

3>如何仅在堆栈上而不是在堆上创建对象

2 个答案:

答案 0 :(得分:4)

如果只想在Heap中创建对象,请将析构函数设置为私有。一旦析构函数变为私有,代码将在堆栈上创建对象时给出编译器错误。如果不使用new,则将在堆栈上创建对象。

1)仅在堆上创建对象

class B 
{ 
    ~B(){}  
    public: 
         void Destroy() 
         { 

            delete this; 
         } 

}; 

  int main() { 
  B* b = new B(); 
  b->Destroy(); 

  return 0; 

}

上面的代码似乎没有错,如果你试图在堆栈B b1上创建对象,它将给编译器错误。

2)为了限制堆上的对象创建,将operator new设为private。

你编码

class B
{
    B(){}   
    public:
    static B* Create()
    {

        return new B();
    }



};

int main() {
 //B S;
   B* b = B::Create();

   return 0;
 }

此代码仍在Heap / Free商店中创建对象,因为它正在使用new。

3)要仅在不在堆上的堆栈上创建对象,应限制使用new运算符。这可以实现将operator new作为私有。

  class B 
   { 
    Private:
        void *operator new(size_t);
        void *operator new[](size_t);
}; 

  int main() { 
  B b1; // OK
  B* b1 = new B() ; // Will give error.

  return 0; 

}

答案 1 :(得分:0)

查看Concrete Data Type idiom:通过使用免费商店(堆)允许或禁止动态分配来控制对象的范围和生命周期

相关问题