简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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