小编Cha*_*les的帖子

为什么在正确编译c ++类构造函数后发生运行时错误

当我运行时./out,它会抛出错误通知,如下所示:

[1]    66798 segmentation fault  ./a.out
Run Code Online (Sandbox Code Playgroud)

但它可以无错误地传递编译器:

clang++ -std=c++11 -g test.cpp
Run Code Online (Sandbox Code Playgroud)

像这样的代码,我发现它靠近hobby->push_back(hb)gdb.

#include <iostream>
#include <string>
#include <vector>
#include <memory>

using namespace std;

struct X {
public:
    X(const string &, const unsigned, const string &);
    X(const X &);
    X &operator=(const X &);
    ~X();
    void print();
private:
    string name;
    unsigned age;
    shared_ptr<vector<string>> hobby;
};

X::X(const string &nm, const unsigned ae, const string &hb):
    name(nm), age(ae)
{
    hobby->push_back(hb);
    cout << "X()" << endl;
}

X::X(const X &obj)
{ …
Run Code Online (Sandbox Code Playgroud)

c++

3
推荐指数
1
解决办法
72
查看次数

C++ 在allocator&lt;string&gt; 中销毁元素时会导致双重释放吗?

C++ 分配器。我知道 String 将分配一个new内部实现的块缓冲区,并在析构函数中释放它(调用 delete[])。

我的问题是使用时是否会免费加倍allocator<string>

  1. 首先在字符串析构函数处释放。
  2. 第二个释放缓冲区指向字符串已空闲。

另外,string的buffer地址是否和allocate(n)region相同?

#include <iostream>
#include <memory>
#include <string>

using namespace std;

int main(int argc, char **argv)
{
    const int cnt = 10;
    allocator<string> alloc;
    auto p = alloc.allocate(cnt);

    alloc.construct(p);
    for (int i = 0; i < cnt; ++i)
    {
        cout << p+i << endl; // print buffer address
    }

    alloc.destroy(p); // will it free buffer of string?

    alloc.deallocate(p, cnt); // will it free buffer of string again? …
Run Code Online (Sandbox Code Playgroud)

c++ std allocator

3
推荐指数
2
解决办法
327
查看次数

标签 统计

c++ ×2

allocator ×1

std ×1