繁体   English   中英

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

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

我正在实现堆栈参考。 但是我得到了“分段错误(核心已转储)”的错误。 我在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;
}

尽可能停止使用new

#include <iostream>
#include <stack>

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

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

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

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

#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