Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

memory management - Does C++11 have wrappers for dynamically-allocated arrays like Boost's scoped_array?

I often need to deal with dynamically-allocated arrays in C++, and hence rely on Boost for scoped_array, shared_array, and the like. After reading through Stroustrup's C++11 FAQ and the C++11 Reference Wiki, I could not find a suitable replacement for these dynamic array wrappers that is provided by the C++11 standard. Is there something that I have overlooked, or do I have to continue relying on Boost?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a specialization of unique_ptr, like unique_ptr<T[]>.

#include <iostream>
#include <memory>

struct test
{
  ~test() { std::cout << "test::dtor" << std::endl; }
};

int main()
{
  std::unique_ptr<test[]> array(new test[3]);
}

When you run it, you will get this messages.

test::dtor
test::dtor
test::dtor

If you want to use shared_ptr, you should use std::default_delete<T[]> for deleter since it doesn't have one like shared_ptr<t[]>.

std::shared_ptr<test> array(new test[3], std::default_delete<test[]>());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...