C++ 智能指针和动态内存

本贴最后更新于 2425 天前,其中的信息可能已经时过境迁

智能指针的创建

shared_ed<string> p1;
shared_ed<list<int>> p2;

shared_ptr<int> p3 = make_shared<int>(42);
//一个指向42的智能指针
shared_ptr<string> p3 = make_shared<int>(10,'9');
//一个指向string9999999的智能指针
shared_ptr<int> p3 = make_shared<int>();
//指向一个值初始化的指针。
void cunc(shared_ptr<vector<int>> &p) 
{
	int x;
	while (cin >> x)
	{
		p->push_back(x);
	}
	for (auto &x : *p)
		cout << x << endl;
}
int  main(){
	auto p = make_shared<vector<int>>();
	cunc(p);
	system("pause");
    return 0;
}

shared_ptr 和 new 结合使用

shared_ptr<int> p2(new int(42));//p2 指向一个值为42的int

int  main(){
	const char *c1 = "hello";
	const char *c2 = "World";
	
	char *r = new char[strlen(c1) + strlen(c2) + 1];
	strcpy(r, c1);
	strcpy(r, c2);
	cout << r << endl;

	string s1 = "hello wordde";
	string s2 = "heyanggegeg";
	strcpy(r, (s1 + s2).c_str());
	cout << r << endl;

	delete [] r;
	
	system("pause");
    return 0;
}

shared_ptr 和 new 使用

如果我们不初始化一个只能指针就会初始成为一个空的指针,
接受指针参数指针的构造函数是 explicit 的,因此我们不能将一个内置指针隐式转换成为一个智能的

shared_ptr<int> p1 = new int(1024); //错误:必须使用直接初始化
shared_ptr<int> p2(new int(1024)); //正确:必须使用直接初始化

# 动态数组怎么用?
使用完成动态数组时候,可以使用delete [] p;

class StrBlob {
public:
typedef std::vector::size_type size_type;
StrBlob();
StrBlob(std::initializer_list il);
size_type size()const { return data->empty(); };
void push_back(const std::string &t) { data->push_back(t); }
void pop_back();
std::string& front();
std::string& back();
private:
std::shared_ptr> data;
void check(size_type i, const std::string &msg) const;
};
StrBlob::StrBlob() :data(make_shared<vector>()) {}
StrBlob::StrBlob(initializer_list li) :
data(make_shared<vector>(li)) {}
void StrBlob::check(size_type i, const string &msg) const
{
if (i >= data->size())
throw out_of_range(msg);
}
string& StrBlob::front() {
check(0, "front on empty StrBlob");
return data->front();
}
string& StrBlob::back()
{
check(0, "back on empty StrBlob");
return data->back();
}
void StrBlob::pop_back()
{
check(0, "pop_back on empty StrBlob");
data->pop_back();
}
void cunc(shared_ptr<vector> &p)
{
int x;
while (cin >> x)
{
p->push_back(x);
}
for (auto &x : *p)
cout << x << endl;
}
int x;
auto vec = new vector();
while (cin>>x)
{
vec->push_back(x);
}
for (auto &x : *vec)
cout << x << endl;
delete(vec);

  • C++

    C++ 是在 C 语言的基础上开发的一种通用编程语言,应用广泛。C++ 支持多种编程范式,面向对象编程、泛型编程和过程化编程。

    106 引用 • 152 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • wizardforcel

    不要用 new

    auto p = make_shared<Type>(args);