如果'Test'是一个普通的类,那么之间有什么区别:
Test* test = new Test;
Run Code Online (Sandbox Code Playgroud)
和
Test* test = new Test();
Run Code Online (Sandbox Code Playgroud) 我正在编写一个内部循环,需要将structs放在连续的存储中.我不知道有多少这些struct会提前出现.我的问题是STL vector将其值初始化为0,所以无论我做什么,我都要承担初始化的成本以及将struct成员设置为其值的成本.
有没有办法阻止初始化,或者是否有一个类似STL的容器,那里有可调整大小的连续存储和未初始化的元素?
(我确信这部分代码需要进行优化,我确信初始化是一项重要的成本.)
另外,请参阅下面的评论,以了解初始化发生的时间.
一些代码:
void GetsCalledALot(int* data1, int* data2, int count) {
int mvSize = memberVector.size()
memberVector.resize(mvSize + count); // causes 0-initialization
for (int i = 0; i < count; ++i) {
memberVector[mvSize + i].d1 = data1[i];
memberVector[mvSize + i].d2 = data2[i];
}
}
Run Code Online (Sandbox Code Playgroud) 我有模板化的gray_code类,它用于存储一些无符号整数,其基础位以格雷码顺序存储.这里是:
template<typename UnsignedInt>
struct gray_code
{
static_assert(std::is_unsigned<UnsignedInt>::value,
"gray code only supports built-in unsigned integers");
// Variable containing the gray code
UnsignedInt value;
// Default constructor
constexpr gray_code()
= default;
// Construction from UnsignedInt
constexpr explicit gray_code(UnsignedInt value):
value( (value >> 1) ^ value )
{}
// Other methods...
};
Run Code Online (Sandbox Code Playgroud)
在一些通用算法中,我写了这样的东西:
template<typename UnsignedInt>
void foo( /* ... */ )
{
gray_code<UnsignedInt> bar{};
// Other stuff...
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我期望bar零初始化,因此bar.value要进行零初始化.但是,在遇到意外错误之后,似乎bar.value用垃圾(确切地说是4606858)初始化而不是0u.这让我感到惊讶,所以我去了cppreference.com,看看上面那条线应该做什么......
根据我的内容,表单T object{};对应于 …
我有兴趣构建一个uninitialized_vector容器,它在语义上std::vector与警告相同,否则将使用无参数构造函数创建的新元素将在没有初始化的情况下创建.我主要是想避免将POD初始化为0. 据我所知,通过std::vector与一种特殊的分配器结合,无法实现这一点.
我想以同样的方式构建我的容器std::stack,它适应用户提供的容器(在我的情况下std::vector).换句话说,我想避免重新实现整体,std::vector而是围绕它提供一个"立面".
有没有一种简单的方法来控制"外部"的默认构造std::vector?
这是我到达的解决方案,这启发了Kerrek的答案:
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
#include <cassert>
// uninitialized_allocator adapts a given base allocator
// uninitialized_allocator's behavior is equivalent to the base
// except for its no-argument construct function, which is a no-op
template<typename T, typename BaseAllocator = std::allocator<T>>
struct uninitialized_allocator
: BaseAllocator::template rebind<T>::other
{
typedef typename BaseAllocator::template rebind<T>::other super_t;
template<typename U>
struct rebind
{
typedef uninitialized_allocator<U, BaseAllocator> …Run Code Online (Sandbox Code Playgroud) c++ ×6
c++-faq ×2
constructor ×2
stl ×2
vector ×2
c++14 ×1
new-operator ×1
optimization ×1
scope ×1
types ×1