Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 初始化列表与静态常量初始化_C++_Constructor_Static Variables_Initialization List - Fatal编程技术网

C++ 初始化列表与静态常量初始化

C++ 初始化列表与静态常量初始化,c++,constructor,static-variables,initialization-list,C++,Constructor,Static Variables,Initialization List,创建100多个新对象时,什么速度更快: //initialization list struct struct_Obj { ...tonsOfVars struct_Obj() : tonsOfVars(init) {} } 或: TonsOfVars意味着多个不同的变量(从POD到结构/类) 我假设static const,因为它调用复制构造函数(意味着1 op?)而不是调用初始化列表中的每个初始值设定项? 虽然对此的常见响应是“profile it”,但即使

创建100多个新对象时,什么速度更快:

//initialization list
    struct struct_Obj {
    ...tonsOfVars
    struct_Obj() : tonsOfVars(init) {}
    }
或:

TonsOfVars意味着多个不同的变量(从POD到结构/类)

我假设static const,因为它调用复制构造函数(意味着1 op?)而不是调用初始化列表中的每个初始值设定项?

虽然对此的常见响应是“profile it”,但即使这样做也不能解释为什么它更快。

这实际上取决于
tonsOfVars
中的类型

我假设static const,因为它调用复制构造函数(意味着1 op?)而不是调用初始化列表中的每个初始值设定项

它正在为
struct\u Obj
调用一个复制构造函数,但仍需要为每个字段调用复制构造函数


如果它们都是POD数据,那就没有什么区别了。但是,在某些类型中,默认构造函数可能比复制构造函数更快(或更慢),因此这会有所不同。

我认为这取决于tonsOfVars的构造函数的速度与tonsOfVars的复制构造函数的速度,如果它们都是编译器生成的或进行浅层复制,然后我想不出为什么初始化列表没有更快


取决于tonsOfVars是什么类型,编译器的优化也会有所不同。

关于默认构造函数的有趣之处->运算符=使第二个变慢。谢谢:)@VeNoM对不起,那是个错误。它应该只运行复制构造函数,而不是
操作符=
。同样,这取决于
tonsOfVars
中的类型。如果我不得不冒险猜测,假设tonsOfVars是原语,并且您的初始化器将使用常量值初始化,我会说默认构造函数会更快。
//static const already constructed, call the copy constructor(?)
static const struct_Obj defaultStruct_Obj = { tonsOfVars(init) };
struct_Obj newObj = defaultStruct_Obj