如果类中存在向量成员,为什么基本类型int x会被初始化



如果我用另一个基本类型变量(例如int y(替换向量成员,x不会像预期的那样初始化。向量成员对成员x做了什么,这使得x被初始化,即使它在声明时没有初始化,基本类型也不应该在创建时初始化?

#include <vector>
#include <iostream>
class Buffer
{
private:
std::vector<char> buffer;
int x;
public:
Buffer(int width, int height) // buffer gets initialized to size 0, and x gets initialized to 0
{
buffer.resize(width * height); // buffer gets resized to argument values
}
};

int main()
{
Buffer screen_2(10,10); // member x get initialized to 0
return 0;
}

x未初始化。从中读取会导致未定义的行为,这可能会产生任何影响,包括每次都给您0

你可以检查生成的程序集来了解到底发生了什么,但我看不出它有多大价值

最新更新