可能吗?std::vector<double> my_vec(sz);已分配但未初始化或填充
Is it possible? std::vector<double> my_vec(sz); which is allocated but not initialized or filled
at [C 11中的值initialized对象和std :: vector构造函数,channel72问,
问题:我的理解在这里正确吗?如果T是POD?
答案是否。
我的问题是,"好吧,那是什么?"
Nevin的回答之一暗示了回答我的问题。要澄清,我的问题是,有没有一种方法可以使用std :: vector&lt; double>,而无需免费填充分配的内存或其他?
我不是在要求解决方法,例如以零大小和使用push_back()启动矢量。这并不总是可能,而且此时,我想把它弄清楚,除了我想弄清楚它之外。
我无法获得Nevin的建议,一种自定义分配器的建议。VC 2017RC(Dinkum)以通常难以理解的方式投诉。关于std :: _ wrap_alloc的东西。Nevin的代码不完整,我可能不知道如何完成它。在我看到他的之前,我写了自己的自定义分配器,但我对自己的理解不足以发誓。
。在我对此感到困惑的那段时间里,我本可以为STD :: Vector写一个不太教条的替代品,以及《美国伟大小说》的几章。
hooray!理查德·克里(Richard Critten)进行救援!他在问题下的评论直接导致答案。
零刺激罪魁祸首是默认的分配模板,即std ::分配器。因此,我们替换它,或用分配器适配器对其进行修改。
我对代码进行了一些整理,并扩展了评论。比尔,请随时发布更全面的答案。但是以下功能非常好。
// Allocator adapter
// Given an allocator A, (std::allocator by default), this adapter
// will, when feasible, override A::construct() with a version that
// employs default construction rather than value-initialization.
// "Feasible" means the object (U *ptr) is default-constructable and
// the default constructor cannot throw exceptions.
//
// Thus it thwarts gratuitous initializations to zeros or whatever.
template <typename T, typename A = std::allocator<T>>
class default_init_allocator : public A {
typedef std::allocator_traits<A> a_t;
public:
// http://en.cppreference.com/w/cpp/language/using_declaration
using A::A; // Inherit constructors from A
template <typename U> struct rebind {
using other =
default_init_allocator
< U, typename a_t::template rebind_alloc<U> >;
};
template <typename U>
void construct(U* ptr)
noexcept(std::is_nothrow_default_constructible<U>::value) {
::new(static_cast<void*>(ptr)) U;
}
template <typename U, typename...Args>
void construct(U* ptr, Args&&... args) {
a_t::construct(static_cast<A&>(*this),
ptr, std::forward<Args>(args)...);
}
};
尚未尝试过,但是从一些谷歌搜索中,似乎可以通过为std :: vector提供自定义分配器来做到这一点。查看最后一行https://en.cppreference.com/w/cpp/named_req/defaultinsertable
如果价值定位不良,例如,如果对象是非类型的类型,并且不需要零,则可以通过提供自定义分配器:: construct
来避免它。
您可以用具有分配的内存的数组初始化向量。
Type* typeArray = new Type [size];
vector <Type> typeVec (typeArray, typeArray+size);
这将为您提供分配的内存(虽然这是垃圾),并且您必须谨慎访问它,因为它可以允许您致电 typevec [n] .typeval除非您实际在n
处初始初始化了值,否则它可能会产生不确定的行为。或如果类型是非类型的类型,则该值在n处是剩下的任何东西的值
- 将数组的地址分配给变量并删除
- vector.resize()中的分配错误
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- Win32编译器选项和内存分配
- 函数中堆分配的效果与缺少堆分配的情况
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 获取字符串的长度并将其分配给数组
- 将地址分配给本地指针后,公共对象的变量将消失
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 我在二维向量中是否正确分配了内存
- 正在尝试重载二进制搜索树分配运算符
- GlobalAlloc而不是其他分配方法
- 自定义先决条件对移动分配运算符有效吗
- 我可以重新分配/覆盖std::字符串吗
- 在c++中使用动态分配的问题
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 为什么我可以使用比分配的内存更多的内存
- 可能吗?std::vector<double> my_vec(sz);已分配但未初始化或填充