以下代码无法编译并出现错误:
“/usr/include/c++/9/bits/shared_ptr.h:106:8:错误:没有命名的类型 在“struct std::enable_if
”中“输入”。
我是 C++ 模板的新手。有人可以解释一下这个错误的含义以及为什么代码无法成功编译吗?
#include <memory>
int main() {
int(*p)[10] = new int[10][10];
std::shared_ptr<int[10]> sp(p);
return 0;
}
添加: 我发现下面的代码编译成功。让我困惑的是 sp0 和 sp1 的含义如此不同,但两者都可以接受 q 作为参数。这是为什么?
#include <memory>
int main() {
int*q = new int;
std::shared_ptr<int> sp0(q);
std::shared_ptr<int[10]> sp1(q);
return 0;
}
像这样使用 std::vectorstd::array
请注意:在当前的 C++ 中几乎不需要裸露的 new/delete,首先查看容器(向量/映射)等。然后考虑 std::make_unique (当您有具有虚拟方法的对象时)。然后考虑 std::make_shared。仅在极少数情况下(在数据结构类内)您可能会遇到 new/delete。
#include <array>
#include <vector>
#include <iostream>
//example of how to pass your dynamically allocated array around
// you could also make an alias
// using my_array_t = std::vector<std::array<int, 3>> and use that throughout your code
void print_dynamically_allocated_array(const std::vector<std::array<int, 3>>& values)
{
// whenever you can use range based for loops
// the cannot go out of bound (avoids bugs)
for (const auto& dynamically_allocated_row : values)
{
for (const int value : dynamically_allocated_row)
{
std::cout << value << " ";
}
std::cout << "\n";
}
}
int main()
{
// initialize a dynamically allocated array of arrays of 3 int values.
// do NOT use make_shared unless you really are sure by design you
// have shared owndership of the data
std::vector<std::array<int, 3>> values{ {1,2,3}, {4,5,6}, {7,8,9} };
print_dynamically_allocated_array(values);
// now the std::vector will go out of scope
// and deallocate any memory it dynamically allocated for you
return 0;
}