如何在C ++ 11中声明堆栈引用?

时间:2015-12-24 06:24:58

标签: c++ c++11 stack

我正在实现堆栈引用。但是我收到了“Segmentation fault(core dumped)”的错误。我在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;
}

3 个答案:

答案 0 :(得分:8)

尽可能停止使用new

#include <iostream>
#include <stack>

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

答案 1 :(得分:5)

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

#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);
}

答案 2 :(得分:-2)

你必须创建对象然后你可以指向它。

#include<iostream>
#include<stack>

using namespace std;

int main() {
    stack<int> s;
    stack<int>& S = s;
    S.push(4);
    return 0;
}