#include <iostream>
#include <memory>
#include <cstring>
using namespace std;
void test(void)
{
const char *str = "hello";
//g++14特性
std::unique_ptr<char []> p = std::make_unique<char []>(10);
memcpy(p.get(), str, strlen(str));
cout << "p.get(): " << p.get() << endl;
}
int main(int argc, char *const argv[])
{
test();
return 0;
}
$ g++ -std=c++11 test2.cpp
test2.cpp: In function 'void test()':
test2.cpp:22:34: error: 'make_unique' is not a member of 'std'
std::unique_ptr<char []> p = std::make_unique<char []>(10);
^
test2.cpp:22:51: error: expected primary-expression before 'char'
std::unique_ptr<char []> p = std::make_unique<char []>(10);
上述代码,g++11有两项特性不支持:
(1)std::make_unique
(2)std::make_unique<char []>
解决办法:
#include <iostream>
#include <memory>
#include <cstring>
using namespace std;
template <typename T>
class DeleteArray {
public:
void operator() (T *p)
{
cout << "delete array" << endl;
delete [] p;
}
};
void test(void)
{
const char *str = "hello";
#if 0
//g++14特性
std::unique_ptr<char []> p = std::make_unique<char []>(10);
#else
//g++11特性
std::unique_ptr<char, DeleteArray<char>> p(new char[10]);
#endif
memcpy(p.get(), str, strlen(str));
cout << "p.get(): " << p.get() << endl;
}
int main(int argc, char *const argv[])
{
test();
return 0;
}
$ g++ -std=c++11 test2.cpp
$ ./a.out
p.get(): hello
delete array