相关疑难解决方法(0)

什么是int()调用?

它已被反复重复,原始类型没有构造函数.例如_bar,当我调用时,这不会初始化为0 Foo():

class Foo{
    int _bar;
};
Run Code Online (Sandbox Code Playgroud)

所以显然int()不是构造函数.但它的名字什么?

在这个例子中我会说i:(构造?初始化?fooed?)

for(int i{}; i < 13; ++i)
Run Code Online (Sandbox Code Playgroud)

Loki Astari 在这里提到该技术有某种名称.

编辑回应Mike Seymour:

#include <iostream>

using namespace std;

class Foo{
    int _bar;
public:
    void printBar(){ cout << _bar << endl; }
};

int main()
{
    Foo foo;

    foo.printBar();

    Foo().printBar();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Visual Studio 2013上运行此代码产生:

3382592
3382592

有趣的是gcc 4.8.1收益率:

134514651
0

c++ primitive construction initialization nomenclature

15
推荐指数
2
解决办法
2193
查看次数

为什么allocate_shared和make_shared这么慢

我刚刚编写了一个测试程序,以找到分配和释放许多管理对象的最快方法shared_ptr.

我试图shared_ptrnew,shared_ptrpool,make_shared,allocate_shared.是什么让我感到惊讶的allocate_shared是慢shared_ptrpool.

vs2017+win10用发布版本测试代码.发布版本设置为默认值(/ O2).我也测试它gcc4.8.5+centos6.2g++ -std=c++11 -O3.

代码是:

#include <memory>
#include <iostream>
#include <vector>
#include <assert.h>
#include <chrono>
#include <mutex>
using namespace std;

struct noncopyable {
protected:
    noncopyable() = default;
    ~noncopyable() = default;
private:
    noncopyable(const noncopyable&) = delete;
    noncopyable& operator=(const noncopyable&) = delete;
    noncopyable(noncopyable&&) = delete;
    noncopyable& operator=(noncopyable&&) = delete;
};

class BlockPool : noncopyable …
Run Code Online (Sandbox Code Playgroud)

c++ performance shared-ptr c++11

9
推荐指数
1
解决办法
713
查看次数

为什么c ++使用memset(addr,0,sizeof(T))来构造一个对象?标准版还是编译错误?

这个问题与我的另一篇文章有​​关:为什么allocate_shared和make_shared这么慢

在这里,我可以更清楚地描述这个问题.

考虑以下代码:

struct A {
    char data_[0x10000];
};

class C {
public:
    C() : a_() { }
    A a_;
};

int main() {
    C c;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我发现代码中C() : a_(),编译器使用A memset(addr,0,0x10000)作为构造函数.如果类型A有一个空构造函数,则asm代码是正确的.

为了更清楚地描述问题,我写了一些测试代码:

#include <stdlib.h>

struct A {
    //A() {}
    char data_[0x10000];
    void dummy() { // avoid optimize erase by compiler
        data_[rand() % sizeof(data_)] = 1;
    }
    int dummy2() { // avoid optimize erase by compiler
        return data_[0];
    }
};

class B {
public:
    template<class …
Run Code Online (Sandbox Code Playgroud)

c++ constructor perfect-forwarding c++11

5
推荐指数
1
解决办法
626
查看次数