【问题标题】:How can I declare a stack reference in C++11?如何在 C++11 中声明堆栈引用?
【发布时间】:2016-03-30 15:09:55
【问题描述】:

我正在实现一个堆栈引用。但是我得到了“分段错误(核心转储)”的错误。我在 Ubuntu 14.04 上使用 g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2。非常感谢。

代码如下。

#include<iostream>
#include<stack>

using namespace std;

int main() {
    stack<int>* S;
    S->push(4);
    return 0;
}

【问题讨论】:

  • 那是一个指针。不是参考。另外,你为什么需要它?从您的示例中不清楚。

标签: c++ c++11 stack


【解决方案1】:

尽可能停止使用new

#include <iostream>
#include <stack>

int main() {
    std::stack<int> s;
    s.push(4);
    return 0;
}

【讨论】:

    【解决方案2】:

    通常不鼓励使用表示对象所有权的“裸”指针,因为它容易出错。要么使用自动变量,要么使用库提供的智能指针。

    #include <stack>
    #include <memory>
    
    int main()
    {
        // On the stack, local scope. This is the fastest;
        // unlike Java we don't have to "new" everything. 
        std::stack<int> s1;
        s1.push(4);
    
        // Dynamically allocated, gets auto-deleted when the
        // last copy of the smartpointer goes out of scope.
        // Has some overhead, but not much.
        // Requires some extra plumbing if used on arrays.
        auto s2 = std::make_shared<std::stack<int>>();
        auto s2_copy(s2); // can be copied
        s2->push(4);
    
        // Dynamically allocated, gets auto-deleted when the
        // smartpointer goes out of scope. No overhead, but
        // cannot be copied / shared.
        // Works out-of-the-box with arrays as well.
        auto s3 = std::make_unique<std::stack<int>>();
        s3->push(4);
    }
    

    【讨论】:

      【解决方案3】:

      您必须创建对象然后才能指向它。

      #include<iostream>
      #include<stack>
      
      using namespace std;
      
      int main() {
          stack<int> s;
          stack<int>& S = s;
          S.push(4);
          return 0;
      }
      

      【讨论】:

      • 尽可能停止使用new
      • @Danh 同意。我更喜欢使用 unique_ptr 和 shared_ptr。
      • 为什么不直接在栈中分配(自动内存)?
      • 至少修复你引入的内存泄漏,不是吗?还提到指针不是引用?
      • 此外,问题中没有任何内容表明他们想在“堆”中分配堆栈对象。
      猜你喜欢
      • 1970-01-01
      • 2014-01-22
      • 2010-09-08
      • 2016-02-04
      • 2018-06-13
      • 2017-06-01
      • 2017-07-19
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多