簡體   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