Its been a while since I have done C++ and I was wondering if someone could help me understand local variables and what happens they go out of scope
So I have this method for creating a vertex shader and it returns a custom class called VertexShader. But before it returns the VertexShader it places it into a std::unsorted_map called vertexShaders
//Declared at the ShaderModule class level. Map to store VertexShaders in
std::unordered_map<LPCSTR, VertexShader> vertexShaders;
//Method to create a vertex shader. Returns a VertexShader
VertexShader ShaderModule::createVertexShader(LPCWSTR fileName, LPCSTR id, LPCSTR entryPoint, LPCSTR targetProfile)
{
ID3DBlob *shaderCode = compileShaderFromFile(fileName, entryPoint, targetProfile);
D3D11_INPUT_ELEMENT_DESC inputElementDescription[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
VertexShader vertexShader(id); //Create a new VertexShader
device->CreateVertexShader(shaderCode->GetBufferPointer(), shaderCode->GetBufferSize(), NULL, &vertexShader.shader);
device->CreateInputLayout(inputElementDescription, 2, shaderCode->GetBufferPointer(), shaderCode->GetBufferSize(), &vertexShader.inputLayout);
shaderCode->Release();
vertexShaders[id] = vertexShader; //Place into the VertexShader map. Places copy?
return vertexShader;
}
Now at the end of the method, right as the return is done, I see that the destructor for my variable vertexShader gets called. And this might sound ridiculous, but I really dont understand why?
Shouldn't it live on in memory since it was placed into the vertexShaders map and only when the vertexShaders map is destroyed then the deconstructor for my VertexShader is called? By doing vertexShaders[id] = vertexShader am I really just making a copy and then eventually another deconstructor for the VertexShader placed into the map will be called?
Also when using the method the destructor is called twice? VertexShader being returned from the method now also getting destroyed?
//Declaration of the vertex shader. Done at the class level
VertexShader vShader;
//Method that uses the createVertexShader
void GraphicsSystem::initialize(HWND windowHandle)
{
/* Other init code*/
vShader = shaderModule.createVertexShader(L"default.shader", "VertexShader", "VShader", "vs_4_0");
}
↧