简体   繁体   English

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

[英]How can I declare a stack reference in C++11?

I am implementing a stack reference. 我正在实现堆栈参考。 However I got the error of 'Segmentation fault (core dumped)'. 但是我得到了“分段错误(核心已转储)”的错误。 I am using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 on Ubuntu 14.04. 我在Ubuntu 14.04上使用g ++(Ubuntu 4.8.2-19ubuntu1)4.8.2。 Many thanks. 非常感谢。

The code is listed below. 该代码在下面列出。

#include<iostream>
#include<stack>

using namespace std;

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

Stop using new wherever you can. 尽可能停止使用new

#include <iostream>
#include <stack>

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

Having "naked" pointers representing object ownership is generally discouraged, as it is error-prone. 通常不建议使用代表对象所有权的“裸”指针,因为它容易出错。 Either use automatic variables, or the smart pointers provided by the library. 要么使用自动变量,要么使用库提供的智能指针。

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

you have to create the object then you can point to it. 您必须创建对象,然后可以指向它。

#include<iostream>
#include<stack>

using namespace std;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM