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

use*_*287 1 c++ object

仅在堆上创建对象-> 1> 代码中是否有任何错误

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

delete this; 
} 

}; 

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

return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

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

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

        return new B();
    }

};

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

Aja*_*jay 6

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

1) 仅在堆上创建对象

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

            delete this; 
         } 

}; 

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

  return 0; 

}
Run Code Online (Sandbox Code Playgroud)

上面的代码似乎没有什么问题,如果您尝试在堆栈上创建对象,B b1则会出现编译器错误。

2) 为了限制在堆上创建对象,将 operator new 设为私有。

你编码

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

        return new B();
    }



};

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

   return 0;
 }
Run Code Online (Sandbox Code Playgroud)

此代码仍在使用新的堆/空闲存储上创建对象。

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; 

}
Run Code Online (Sandbox Code Playgroud)