当我运行时./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++ 分配器。我知道 String 将分配一个new内部实现的块缓冲区,并在析构函数中释放它(调用 delete[])。
我的问题是使用时是否会免费加倍allocator<string>?
另外,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)