Destroying vectors of dynamic arrays via destructor in c++ - c++

I'm working on one of assignments to do with image manipulation (blending and zooming) and I've ran into a problem that I have hard time overcoming.
Structure of my application
Class Image
rgb struct: contains floats (they're flattened pixels) and overloaded operators.
pixels: a 1d array of pixels which is initialized via constructor to be h * w
Class destructor.
Destructor looks a little like this...
virtual ~Image()
{
if (pixels != NULL)
delete[] pixels;
}
Now I'm using another class called Filter which inherits from Image
class Filter: public class Image
std::vector of Image imgStack; Container for images that I'm going to blend
std::vector of Rgb pixelBuffer; A container for the pixels for each images one pixel. This is not dynamic so I'm not worried about deleting this.
Destructor for the derived class.
~Blend()
{
delete &imageStack;
}
what this part of my main.cpp looks like...
while (userInput != 5)
{
switch(userInput)
case 1:
{
Blend *meanImage = new Blend(3263, 2505, 13);
meanImage->writePPM("Mean_" + std::to_string(count) + ".ppm");//every iteration, the file name is unique
meanImage->~Blend();
}
}
In my main.cpp I'm basically running 13 images into the Blend object which stores the images in the vector container to do all my functionality on. During the run time the space used is around 1.3GB, but since my object is in a loop (i have a menu for multiple functionality) the object doesn't usually leave the scope so the destructor isn't automatically called, so I call it manually like this; medianImage->~Blend(); Now the all the error says is that my application "has triggered a breakpoint" and that's it... Note, no breakpoint is found anywhere. I'm aware that it's generally bad to use dynamic arrays because it causes all sorts of memory problems (if it's done by me), but I want to fix this just so I know how to solve these in the future.
If you have any questions of the code, I can post snippers.
Edit: here's an my Blend class.
#pragma once
#include "stdafx.h"
#include "Image.h"
#include <vector>
#include <string>
class Blend : public Image
{
private:
std::vector<Image> imageStack;
std::vector<Rgb*> pixelBuffer;//only works with pointers (no copying)
int m_noOfImages;
Rgb* getMedianFromSet();
Rgb getMeanFromSet();
Rgb getStdDev(Rgb meanPix);
public:
Blend(int width = 0, int height = 0, int noOfImages = 0):Image(width, height), m_noOfImages(noOfImages), imageStack(noOfImages), pixelBuffer(noOfImages)
{}
public:
void stack(bool push = true);
void meanBlend();
void medianBlend();
void sigmaClipping(float sigma = 0.5f);
~Blend()
{
delete &imageStack;
}
};

#pragma once
#include "stdafx.h"
#include "Image.h"
#include <vector>
#include <string>
#include <memory>
class Blend : public Image
{
private:
std::vector<Image> imageStack;
// Changed to shared_ptr<T> could use unique_ptr<T> depending on need.
std::vector<std::shared_ptr<Rgb>> pixelBuffer;//only works with pointers (no copying)
int m_noOfImages;
Rgb* getMedianFromSet();
Rgb getMeanFromSet();
Rgb getStdDev(Rgb meanPix);
public:
Blend(int width = 0, int height = 0, int noOfImages = 0):Image(width, height), m_noOfImages(noOfImages), imageStack(noOfImages), pixelBuffer(noOfImages)
{}
public:
void stack(bool push = true);
void meanBlend();
void medianBlend();
void sigmaClipping(float sigma = 0.5f);
// Clear Entire Buffer
void cleanup() {
// When using the heap with smart pointers
for ( auto item : containerVariable ) {
item.reset();
item = nullptr;
}
containerVariable.clear();
}
// Remove Single Element
void remove( unsigned idx ) {
// Write function to remove a single element from vector
}
~Blend()
{
// This is definitely wrong here: You are trying to delete a reference
// to a template container that is storing `Image` objects that
// are on the stack.
// delete &imageStack;
}
};
It is better to write a function to clean up memory, and to remove specific elements from containers when using dynamic memory than it is to use a class's destructor.

Related

trying to insert a vector to an unordered_map but get "message : see reference to class template instantiation"

I'm trying to make an ecs and this is my code
#include "pandaFramework.h"
#include "pandaSystem.h"
#include <unordered_map>
#include <vector>
#include <memory>
#include <iostream>
struct Component {
NodePath* node_path;
Component(NodePath* path) {
node_path = path;
}
void start(){}
void update(){}
};
struct Spinner : Component {
void update() {
std::cout << "Hello World!\n";
}
};
class Scene : public NodePathCollection {
public:
std::unordered_map<NodePath*, std::vector<std::unique_ptr<Component>>> components;
void add_path(NodePath node_path) {
NodePathCollection::add_path(node_path);
std::vector<std::unique_ptr<Component>> empty;
components[&node_path] = std::move(empty);
}
template<typename ComponentType>
void add_component(NodePath* node_path) {
components[node_path].push_back(std::make_unique<ComponentType>(node_path));
}
};
int main(int argc, char* argv[]) {
// Load the window and set its title.
PandaFramework framework;
framework.open_framework(argc, argv);
framework.set_window_title("My Panda3D Window");
WindowFramework* window = framework.open_window();
// Load the environment model.
NodePath scene = window->load_model(framework.get_models(), "models/environment");
Scene s;
s.add_path(scene);
s.add_component<Spinner>(&scene);
// Reparent the model to render.
scene.reparent_to(window->get_render());
// Apply scale and position transforms to the model.
scene.set_scale(0.25f, 0.25f, 0.25f);
scene.set_pos(-8, 42, 0);
// Run the engine.
framework.main_loop();
// Shut down the engine when done.
framework.close_framework();
return 0;
}
And when I use add_object I get
"message : see reference to class template instantiation 'std::vectorstd::unique_ptr<Component,std::default_delete<Component>,std::allocatorstd::unique_ptr<Component,std::default_delete<Component>>>' being compiled"
What should I do?
There are multiple fundamental bugs with the shown code.
You will get the same compilation error with the following code, as well:
std::vector<std::unique_ptr<Component>> empty;
std::vector<std::unique_ptr<Component>> empty2=empty;
A std::unique_ptr, by definition, a one and only pointer to the same underlying object. There are no others. For that reason is why std::unique_ptr does not have a copy constuctor. A std::unique_ptr cannot be copied. This is an absolute rule. No exceptions. The above code attempts to copy a vector of std::unique_ptrs. Since they cannot be copied, this fails. The fact that, in this instance, the vectors are empty is immaterial.
void add_object(Object object) {
std::vector<std::unique_ptr<Component>> empty;
components[&object] = empty;
}
The assignment operator effectively attempts to make a copy of the vector, and this fails for the same reason.
It's possible to make this work using move semantics:
components[&object] = std::move(empty);
This will now compile. But now you have a different bug to deal with.
object is a parameter to this function.
When this function returns, all of its parameters get destroyed. They will no longer exist. They will cease to exist. They will become no more. They will be come ex-objects.
And the code above will be left with a pointer to a destroyed object in the unordered map. Whatever happens to touch that pointer, from that point on, by definition, will be undefined behavior. You will need to fix this as well.
The problem is very layered, as mentioned in Sam's answer. One problem is that you lack a proper copy constructor for the Component class. This can be solved by not using a temporary variable as shown in the code below:
class Scene {
public:
std::unordered_map<Object*, std::vector<std::unique_ptr<Component>>> components;
void add_object(Object object) {
// std::vector<std::unique_ptr<Component>> empty;
// Adding an empty container at the given key
components[&object] = std::vector<std::unique_ptr<Component>>();
}
};
For the other problems Sam's mentions in his answers, perhaps, instead of using a pointer to an Object, you could use the object instead. This could also lead to the same copy constructor issue, but the code should work with minimal changes.

Initialize nontrivial class members when created by PyObject_NEW

I have a Python object referring to a C++ object.
Header:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>
typedef struct {
PyObject_HEAD
FrameBuffer frame_buffer;
} PyFrameBuffer;
extern PyTypeObject PyFrameBuffer_type;
extern PyObject* PyFrameBuffer_NEW(size_t width, size_t height);
The C++ FrameBuffer class is following:
class FrameBuffer {
public:
explicit FrameBuffer(const size_t width, const size_t height);
// ...
private:
size_t m_width;
size_t m_height;
std::vector<Pixel> m_pixels;
};
Pixel is a simple class of few plain type elements.
The PyFrameBuffer_NEW() function is following:
PyObject* PyFrameBuffer_NEW(size_t width, size_t height)
{
auto* fb = (PyFrameBuffer*) PyObject_NEW(PyFrameBuffer, &PyFrameBuffer_type);
if (fb != nullptr)
{
fb->frame_buffer = FrameBuffer(width, height);
}
return (PyObject*) fb;
}
This code crashs:
fb->frame_buffer is allocated with undefined values (fb->frame_buffer.m_pixels.size() is undefined).
During fb->frame_buffer assignment, there is a deallocation of an undefinied number of Pixel in m_pixels.
And so, it crash.
This code seems to works:
/// ...
if (fb != nullptr)
{
FrameBuffer fb_tmp(width, height);
std::memcpy(&fb->frame_buffer, &fb_tmp, sizeof(FrameBuffer));
}
// ...
But I suspect this is not the proper way to solve this issue (I suspect Pixels in fb_tmp are desallocated outside the scope.
What would the the proper way to solve this problem?
Is there a commonly known approach on how to expose complex object in CPython?
I've successfully used code similar to
typedef struct {
PyObject_HEAD
FrameBuffer *frame_buffer;
} PyFrameBuffer;
and then
if (fb != nullptr)
{
fb->frame_buffer = new FrameBuffer( ... );
}
But you have to account for deleting the object explicitly. You'll need to add a tp_dealloc() function to your PyFrameBuffer initialization that deletes the C++ FrameBuffer object:
delete fb->frame_buffer;
Also:
When you use C++ to create a Python extension module, you're linking in your code's C++ runtime libraries. If more than one module uses C++, they all have to use the exact same C++ runtime libraries.

C++ Vector read access violation Mylast returned 0x8

I really need help on this one cause I am extremely stuck and have no idea what to do.
Edit:
A lot of you guys are saying that I need to use the debugger but let me be clear I have not used C++ for an extremely long time and I've used visual studio for a grand total of 2 weeks so I do not know all the cool stuff it can do with the debugger.
I am a student at university at the beginning of my second year who is trying to work out how to do something mostly by failing.
I AM NOT a professional coder and I don't have all the knowledge that you people have when it comes to these issues and that is why I am asking this question. I am trying my best to show my issue so yes my code contains a lot of errors as I only have a very basic understanding of a lot of C++ principles so can you please keep that in mind when commenting
I'm only posting this here because I can don't know who else to ask right now.
I have a function called world that is suppose to call my render class to draw all the objects inside of its vector to the screen.
#include "C_World.h"
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
C_World::~C_World()
{
delete[] render;
}
// adds an object to the world vector
void C_World::addToWorld(C_renderable* a)
{
world_list.push_back(a);
}
void C_World::World_Update()
{
render->ClearScreen();
World_Render();
}
void C_World::World_Render() {
for (int i = 0; i < 1; i++)
{
//render->DrawSprite(world_list[i]->getTexture(), world_list[i]->get_X, world_list[i]->get_Y());
render->DrawSprite(1, 1, 1);
}
}
While testing I commented out the Sprites get functions in order to check if they were causing the issue.
the renderer sprites are added to the vector list in the constructor through the create sprite function
C_Renderer::C_Renderer()
{
// test sprite: Id = 1
CreateSprite("WhiteBlock.png", 250, 250, 1);
}
I thought this might of been the issue so I had it in other functions but this didn't solve anything
Here are the Draw and create Sprite functions
// Creates a sprite that is stored in the SpriteList
// Sprites in the spriteList can be used in the drawSprite function
void C_Renderer::CreateSprite(std::string texture_name,
unsigned int Texture_Width, unsigned int Texture_height, int spriteId)
{
C_Sprite *a = new C_Sprite(texture_name,Texture_Width,
Texture_height,spriteId);
SpriteList.push_back(a);
size_t b = SpriteList.size();
HAPI.DebugText(std::to_string(b));
}
// Draws a sprite to the X and Y co-ordinates
void C_Renderer::DrawSprite(int id,int x,int y)
{
Blit(screen, _screenWidth, SpriteList[id]->get_Texture(),
SpriteList[id]->getTexture_W(), SpriteList[id]->getTexture_H(), x, y);
}
I even added some test code into the create sprite function to check to see if the sprite was being added too the vector list. It returns 1 so I assume it is.
Exception thrown: read access violation.
std::_Vector_alloc<std::_Vec_base_types<C_Sprite *,
std::allocator<C_Sprite *> > >::_Mylast(...) returned 0x8.
that is the full error that I get from the compiler
I'm really really stuck if there is anymore information you need just say and ill post it straight away
Edit 2:
#pragma once
#include <HAPI_lib.h>
#include <vector>
#include <iostream>
#include "C_renderable.h"
#include "C_Renderer.h"
class C_World
{
public:
C_World();
~C_World();
C_Renderer *render = nullptr;
void World_Update();
void addToWorld(C_renderable* a);
private:
std::vector<C_renderable*> world_list;
void C_World::World_Render();
};
#pragma once
#include <HAPI_lib.h>
#include "C_renderable.h"
#include "C_Sprite.h"
#include <vector>
class C_Renderer
{
public:
C_Renderer();
~C_Renderer();
// gets a pointer to the top left of screen
BYTE *screen = HAPI.GetScreenPointer();
void Blit(BYTE *destination, unsigned int destWidth,
BYTE *source, unsigned int sourceWidth, unsigned int sourceHeight,
int posX, int posY);
void C_Renderer::BlitBackground(BYTE *destination,
unsigned int destWidth, unsigned int destHeight, BYTE *source,
unsigned int sourceWidth, unsigned int sourceHeight);
void SetPixel(unsigned int x,
unsigned int y, HAPI_TColour col,BYTE *screen, unsigned int width);
unsigned int _screenWidth = 1750;
void CreateSprite(std::string texture_name,
unsigned int Texture_Width,unsigned int Texture_height, int spriteId);
void DrawSprite(int id, int x, int y);
void ClearScreen();
private:
std::vector<C_Sprite*> SpriteList;
};
I don't say this lightly, but the code you've shown is absolutely terrible. You need to stop and go back several levels in your understanding of C++.
In all likeliness, your crash is the result of a simple "shadowing" issue in one or more of your functions:
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
C_World::~C_World()
{
delete[] render;
}
There are multiple things wrong here, and you don't show the definition of C_World but if this code compiles we can deduce that it has a member render, and you have fallen into a common trap.
C_Renderer *render = new C_Renderer;
Because this line starts with a type this is a definition of a new, local variable, render. Your compiler should be warning you that this shadows the class-scope variable of the same name.
What these lines of code
C_World::C_World()
{
// creates an instance of the renderer class to render any drawable objects
C_Renderer *render = new C_Renderer;
}
do is:
. assign an undefined value to `this->render`,
. create a *local* variable `render`,
. construct a dynamic `C_Renderer` presumably on the heap,
. assign that to the *local* variable `render`,
. exit the function discarding the value of `render`.
So at this point the memory is no-longer being tracked, it has been leaked, and this->render is pointing to an undefined value.
You repeat this problem in several of your functions, assigning new results to local variables and doing nothing with them. It may not be this specific instance of the issue that's causing the problem.
Your next problem is a mismatch of new/delete vs new[]/delete[]:
C_World::~C_World()
{
delete[] render;
}
this would result in undefined behavior: this->render is undefined, and delete[] on a non-new[] allocation is undefined.
Most programmers use a naming convention that distinguishes a member variable from a local variable. Two common practices are an m_ prefix or an _ suffix for members, e.g.
class C_World
{
public:
C_Foo* m_foo; // option a
C_Renderer* render_; // option b
// ...
}
Perhaps you should consider using modern C++'s concept of smart pointers:
#include <memory>
class C_World {
// ...
std::unique_ptr<C_Renderer> render_;
// ...
};
C_World::C_World()
: render_(new C_Renderer) // initializer list
{}
But it's unclear why you are using a dynamic allocation here in the first place. It seems like an instance member would be better:
class C_World {
C_Renderer render_;
};
C_World::C_World() : render_() {}

array of object in C++ in sfml

I am trying to use vectors in sfml C++ and I am semi-failing because I am not able to create a vector consisting of 4 RectangleShapes :(
I am skipping some lines of the code which are not causing the problem
This is the code which is working but it is least optimized in my opinion
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <iostream>
#include "mainCharacter.h" // it consists the mainCharacter class
class classBackground{
public:
sf::Texture texture;
sf::Sprite image;
sf::RectangleShape rectTopBorder,rectBotBorder,rectLeftBorder,rectRightBorder;
std::vector<sf::RectangleShape> rect;
classBackground(){
texture.loadFromFile("wagon.png");
image.setTexture(texture);
image.setPosition(300,250);
rectTopBorder.setSize(sf::Vector2f(230,5));
rectTopBorder.setPosition(image.getPosition());
rectTopBorder.move(0,60);
rectBotBorder.setSize(sf::Vector2f(230,5));
rectBotBorder.setPosition(image.getPosition());
rectBotBorder.move(0,225);
rectLeftBorder.setSize(sf::Vector2f(5,170));
rectLeftBorder.setPosition(image.getPosition());
rectLeftBorder.move(0,60);
rectRightBorder.setSize(sf::Vector2f(5,170));
rectRightBorder.setPosition(image.getPosition());
rectRightBorder.move(225,60);
rect.push_back(rectTopBorder);
rect.push_back(rectBotBorder);
rect.push_back(rectLeftBorder);
rect.push_back(rectRightBorder);
}
};
//in the main function
classMainCharacter mainCharacter; ///another class which has collision detection
classBackground background;
///in the loop
for(int i = 0; i<=3; i++){
mainCharacter.collision(background.rect[i]); ///colision is a function in the mainCharacter class (detects collision)
}
And this is the code which I want to work but my game is crushing :(
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <iostream>
#include "mainCharacter.h" // it consists the mainCharacter class
class classBackground{
public:
sf::Texture texture;
sf::Sprite image;
std::vector<sf::RectangleShape> rect; // it doesn't work if I write rect(4) or rect = {rect1,rect2,rect3,rect3} or even rect(4)={rect1,....}
classBackground(){
texture.loadFromFile("wagon.png");
image.setTexture(texture);
image.setPosition(300,250);
rect[0].setSize(sf::Vector2f(230,5));
rect[0].setPosition(image.getPosition());
rect[0].move(0,60);
rect[1].setSize(sf::Vector2f(230,5));
rect[1].setPosition(image.getPosition());
rect[1].move(0,225);
rect[2].setSize(sf::Vector2f(5,170));
rect[2].setPosition(image.getPosition());
rect[2].move(0,60);
rect[3].setSize(sf::Vector2f(5,170));
rect[3].setPosition(image.getPosition());
rect[3].move(225,60);
}
};
//in the main function
classMainCharacter mainCharacter; ///another class which has collision detection
classBackground background;
///in the loop
for(int i = 0; i<=3; i++){
mainCharacter.collision(background.rect[i]); ///colision is a function in the mainCharacter class (detects collision)
}
what am I doing wrong? :(
I tried to defined the rects before vector and then inserting into the vector but it also doesn't work (in such way vector<...> rect = {......}).
Well even if I would not expect to much difference between the two versions, an answer is worth telling anyway as your problem has neither to do with performance nor with sfml at all but is more general.
What you try is to instantiate a class member at its declaration, what is not possible. But what you can do is either one of the following methods:
1) Use the default member initializer with the C++ 11 unified initialization syntax like so (wich may only be syntactic sugar for (2) prior to this: http://en.cppreference.com/w/cpp/language/data_members#Member_initialization):
std::vector<sf::RectangleShape> rect{4}
2) Use the initializer list in the constructor:
classBackground() : rect(4) {...}
3) Or call the resize method in the constructor:
classBackground(){
rect.resize(4);
...
}
The last one might be the worst as it first calls the standard constructor of vector<...> and changes it afterwards.
In the first version, you were successfully creating a vector of 4 elements by using push_back.
In the second version, you never allocate space for your 4 elements, so when you try and assign values to the elements of the vector, that's your crash.
If you really don't want to use push_back you can instead use resize to set the size of the vector.
Here's a simplified version of what you're trying to do
#include <vector>
class classBackground {
std::vector<int> rect;
public:
classBackground() {
rect.resize(4);
rect[0] = 1;
rect[1] = 2;
rect[2] = 3;
rect[3] = 4;
}
};
int main() {
classBackground cb;
// there, it worked.
}
Demo: http://ideone.com/YYq0oA
Alternatively if you have C++11 and your vector is always going to be 4 elements large, which in this case it seems like it might be, you should consider using std::array instead.
#include <array>
class classBackground {
std::array<int, 4> rect;
public:
classBackground() {
rect[0] = 1;
rect[1] = 2;
rect[2] = 3;
rect[3] = 4;
}
};
int main() {
classBackground cb;
// there, it worked.
}
Array works like vector in most ways, you just can't change the size, but it can potentially be more efficient.

Creating a new object destroys an older object with different name in C++

First question here!
So, I am having some problems with pointers in Visual C++ 2008. I'm writing a program which will control six cameras and do some processing on them so to clean things up I have created a Camera Manager class. This class handles all operations which will be carried out on all the cameras. Below this is a Camera class which interacts with each individual camera driver and does some basic image processing.
Now, the idea is that when the manager is initialised it creates two cameras and adds them to a vector so that I can access them later. The catch here is that when I create the second camera (camera2) the first camera's destructor is called for some reason, which then disconnects the camera.
Normally I'd assume that the problem is somewhere in the Camera class, but in this case everything works perfectly as long as I don't create the camera2 object.
What's gone wrong?
CameraManager.h:
#include "stdafx.h"
#include <vector>
#include "Camera.h"
class CameraManager{
std::vector<Camera> cameras;
public:
CameraManager();
~CameraManager();
void CaptureAll();
void ShowAll();
};
CameraManager.cpp:
#include "stdafx.h"
#include "CameraManager.h"
CameraManager::CameraManager()
{
printf("Camera Manager: Initializing\n");
[...]
Camera *camera1 = new Camera(NodeInfo,1, -44,0,0);
cameras.push_back(*camera1);
// Adding the following two lines causes camera1's destructor to be called. Why?
Camera *camera2 = new Camera(NodeInfo,0, 44,0,0);
cameras.push_back(*camera2);
printf("Camera Manager: Ready\n");
}
Camera.h
#include "stdafx.h"
// OpenCV
#include <cv.h>
#include <highgui.h>
// cvBlob
#include "cvblob.h"
// FirePackage
#include <fgcamera.h>
using namespace cvb;
class Camera{
public:
int cameraID;
double x, y,z, FOVx, FOVy;
IplImage *image, *backgroundImage, *labeledImage;
CvBlobs blobs;
Camera(FGNODEINFO NodeInfo[], int camID, float xin, float yin, float zin);
~Camera();
void QueryFrame();
void ProcessFrame();
void GrabBackground();
void LoadCalibration();
void Show();
private:
// ======= FirePackage ======
CFGCamera FGCamera;
UINT32 Result;
FGNODEINFO MyNodeInfo;
UINT32 NodeCnt;
FGFRAME Frame;
// ======= Camera Configuration ======
// Trigger Settings
UINT32 nOn, nPolarity, nSrc, nMode, nParm, BurstCount, DMAMode;
// Image Settings
UINT32 AutoExposure, Shutter, Gain, Brightness, Gamma;
// Image Format Settings
UINT32 Format, Mode, Resolution, ColorFormat, FrameRate;
// Structures
UINT32 TriggerValue;
UINT32 FormatValue;
UINT32 DFormatValue;
// OpenCV Calibration matrices
CvMat *intrinsics, *distortion;
IplImage *mapx, *mapy;
void SetUpFirePackage();
void SetUpOpenCV();
};
Camera.cpp:
#include "stdafx.h"
#include "Camera.h"
Camera::Camera(FGNODEINFO NodeInfo[], int camID, float xin, float yin, float zin)
{
cameraID = camID;
x = xin;
y = yin;
z = zin;
FOVx = 42.6;
FOVy = 32.5;
MyNodeInfo = NodeInfo[cameraID];
SetUpFirePackage();
SetUpOpenCV();
// Grab the first frame
printf("Waiting for frame...\n");
QueryFrame();
};
//Destructor
Camera::~Camera()
{
// Stop the device
FGCamera.StopDevice();
// Close capture
FGCamera.CloseCapture();
// Disconnect before ExitModule
FGCamera.Disconnect();
// Exit module
FGExitModule();
cvReleaseImage(&image);
};
[...]
};
You need to get clear the difference between objects and pointers to objects.
Your CameraManager contains a vector of Camera so you must expect your cameras to be copied as the vector expands. This means that copies will be created and the old copies destroyed at certain points in the lifetime of the container.
This call pushes a copy of the parameter (the camera pointed to by camera1) into the vector.
cameras.push_back(*camera1);
When the second Camera is pushed into the vector it is not the Camera pointed to by camera1 that is destroyed but a copy of this Camera that was pushed into the vector. As a side note, you have a memory (and object) leak as camera1 points to an object that you allocated dynamically with new but which you don't delete.
It sounds as though you are not prepared for your Camera objects to be copied. It may be that you are better off with a container of pointers (or smart pointers to help with clean deallocation) or it may be possible for you to alter the way your Camera class works to cope correctly with being copied. Without seeing the Camera class it is difficult to know which is more appropriate.
You're storing raw pointers in your Camera class, but not defining a copy constructor or assignment operator (both of which std::vector requires for the above to work correctly). So, you get compiler-generated versions that do a shallow copy.
As a result of cameras.push_back(*camera1);, you're actually creating a temporary that is destroyed after the push_back returns. This temporary's destructor will release the resources you allocated in the statement Camera *camera1 = new Camera(NodeInfo,1, -44,0,0);, and the instance in the vector will have pointers to resources that are no longer valid.
You need to either not store the Camera by value in the vector (use a shared pointer of some sort) and explicitly mark the type as noncopyable/assignable, or you should provide the necessary copy/assignment semantics.
Also, not to mention you're leaking both camera1 and camera2.