I'm having memory leak problems with the following line of code:
auto state = newSpriteState();
Where these are the related functions:
class SpriteState {
protected:
Vector3 position;
int width, height;
double rotation, scaling;
int priority;
public:
SpriteState()
: position(0,0,0),
width(1), height(1),
rotation(0), scaling(1.0f),
priority(0)
{}
std::shared_ptr<SpriteState> newSpriteState()
{
return std::make_shared<SpriteState>();
}
};
class Vector3 {
private:
double x, y, z;
public:
Vector3( double x_, double y_, double z_ )
{
x = x_; y = y_; z = z_;
}
};
Intel Inspector continues to report that I'm having a memory leak in
the function newSpriteState(); more specifically std::make_shared<SpriteState>().
UPDATE
Judging from the comments, it seems there may be some external reason for this so here's more code:
bool Sprite::loadImage() {
auto state = newSpriteState();
initStateVector(0, state);
}
where:
class Sprite
{
public:
Sprite();
std::map<const int, const std::shared_ptr<SpriteState>> stateVector;
void initStateVector(const int line, std::shared_ptr<SpriteState>& state)
{
stateVector.clear();
stateVector.insert(std::make_pair( line, std::move(state) ));
}
void loadImage();
}
I've uploaded a simplified version of the Sprite class I'm actually using for clarity.
Basically, I'm allocating a shared_ptr<SpriteState> and sticking into a std::map in class Sprite.
The problem has been solved after an upgrade to vs12. My best estimation is that the problem had something to do with the tr1 implementation of smart pointers.
Related
I'm looking to build a 1D std::array of structs, each of whose size is 16 bytes. The 1D array is a flattening of a class representing a 3D array (basically an std::array wrapper that has some 3D specific operators and other fluff). My first attempt is an array of size 256 x 256 x 32, so roughly 35MB, which throws a SIGSEGV error.
A simplified example of everything looks like this:
Structs.cpp
struct Coord {
int x;
int y;
int z;
Coord() { }
Coord(int x_, int y_, int z_) { x = x_; y = y_; z = z_; }
}
int TR (int arg) {
// ... Some transformation
}
struct MyStruct {
Coord position;
int terrain;
MyStruct() { }
MyStruct(int x_, int y_, int z_, int terrain_) {
terrain = terrain_;
position = Coord(TR(x_), TR(y_), TR(z_));
}
}
ArrayWrapper.hpp
#include <array>
template <typename T, int HSIZE, int VSIZE> struct ArrayWrapper {
private:
std::array<T, HSIZE*HSIZE*VSIZE> narray;
public:
void set(T obj, int x, int y, int z) {
narray[x + z*HSIZE + y*HSIZE*HSIZE] = obj;
}
T& operator() (int x, int y, int z) {
return narray.at(x + z*HSIZE + y*HSIZE*HSIZE);
}
CoordinateMap.cpp
#include "ArrayWrapper.hpp"
#include "Structs.cpp"
const int HSIZE = 256;
const int VSIZE = 32;
class CMap {
private:
ArrayWrapper<MyStruct, HSIZE, VSIZE>* coords_ = new ArrayWrapper<MyStruct, HSIZE, VSIZE>;
ArrayWrapper<MyStruct, HSIZE, VSIZE> coords = *coords_;
public:
// ... Getter, setter, and a bunch of other methods,
~CMap() { delete coords; }
}
If I anywhere try to say CMap something; I get a SIGSEGV. I know that the stack is relatively small, so I'm attempting to allocate this structure on the heap by using new. Many people (on this site and others) say "Finding a large range of contiguous memory is difficult, even if it's on the heap," but don't give an indication of what a reasonable expectation of the size of contiguous memory is. I would think 32MB in a modern-day computer is doable.
What might be throwing a Seg. fault here?
ArrayWrapper<MyStruct, HSIZE, VSIZE> coords = *coords_;
Should be...
ArrayWrapper<MyStruct, HSIZE, VSIZE>& coords = *coords_;
... which makes sense. The 1st line is making a copy of coords_' reference, which, in this case, defeats the purpose of using new, since that copy is put on the stack.
I am working on an API that is supposed to allow you to draw simple geometric shapes and calculate their elements. The project is based on the SFML library.
I have this class:
#ifndef POINT_H_INCLUDED
#define POINT_H_INCLUDED
#include "stdafx.h"
#include "Helper.h"
class Point : public AbstractShape
{
public:
Point(float x, float y);
Vector getCoords();
sf::VertexArray getShape();
void setLabel(std::string label, int param);
private:
float m_x, m_y, m_R;
std::string m_label;
sf::VertexArray m_shape;
sf::Text m_labelObject;
};
#endif
It inherits from the abstract class AbstractShape, just like other similar classes Segment and Triangle. I need this to be able to add the different shapes to a single container to process them conveniently in one place later on.
In the main function, I declare the container, then create an instance of Point and then push_back it to the container:
std::vector<AbstractShape*> shapes;
Point* p1 = new Point(100, 50);
p1->setLabel("A", 4);
shapes.push_back(p1);
I think it would be better if the instance could add itself to the container when the instance is created. To do that, the Point class should be able to see container from within itself. What is the best way to achieve this while not introducing too much coupling to the Point class?
To add itself to the container, the Point needs to be coupled with the container. Coupling the two seems like a bad idea: why should the Point know anything about std::vector?
If you use this pattern often in your code, it's better to define a function to instantiate and add the point to a container:
template<typename T=std::vector<Point*>>
Point *makePoint(int x, int y, T container) {
Point *p = new Point(x, y);
container.push_back(p);
return p; // so we can set other properties easily
}
Or to create another Context class which encapsulates the set of points:
template <typename T=std::vector<Point*>>
class Context {
T container;
public:
Point* addPoint(int x, int y) {
Point *p = new Point(x, y);
container.push_back(p);
return p;
}
};
Also you may wish to use shared_ptr or unique_ptr to avoid memory leaks, though this may get a bit messy with inheritence.
Here's a fully WME on Ideone with the 2nd option:
#include <iostream>
#include <vector>
using namespace std;
class Point {
public:
Point (int x, int y) {}
};
template <typename T=std::vector<Point*>>
class Context {
T container;
public:
Point* addPoint(int x, int y) {
Point *p = new Point(x, y);
container.push_back(p);
return p;
}
};
int main() {
Context<> c;
c.addPoint(1, 2);
return 0;
}
I think it would be better if the instance could add itself to the
container when the instance is created.
This is your decision, but think twice on it - in most situations it is better to keep objects as simple as possible. If you need just to simplify your code, this can be made:
You can make external construction function, similar to std::make_share and std::make_tuple:
This will make you able to call:
construct<Point>(container, 1, 2);
construct<Line>(container, 1, 2, 3, 4);
And it will construct Point/Line and put into container in one line
Full code:
#include <iostream>
#include <vector>
using namespace std;
struct AbstractShape
{
virtual std::ostream& dump(std::ostream&) = 0;
};
struct Point : AbstractShape
{
Point(float x, float y) : x(x), y(y) {}
virtual std::ostream& dump(std::ostream& o) override
{
return o << "P[" << x << ":" << y << "]";
}
float x, y;
};
struct Line : AbstractShape
{
Line(float x1, float y1, float x2, float y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
virtual std::ostream& dump(std::ostream& o) override
{
return o << "L[" << x1 << ":" << y1 << "," << x2 << ":" << y2<< "]";
}
float x1, y1, x2, y2;
};
template<typename Object, typename Container, typename ...Args>
Object* construct(Container& c, Args... args)
{
Object* res = new Object(args...);
c.push_back(res);
return res;
}
int main() {
std::vector<AbstractShape*> container;
construct<Point>(container, 1, 2);
construct<Line>(container, 1, 2, 3, 4);
for (auto s : container)
s->dump(std::cout) << std::endl;
return 0;
}
Output:
P[1:2]
L[1:2,3:4]
Live test
And I definitely recommend using std::unique_ptr instead of raw pointers
I've nested a class for use within another class and need to try accessing individual parts of it but can't. How would I go about doing this?
class Point
{
public:
Point() { float x = 0, y = 0; }
void Input(int &count); //input values
Rectangle myRec;
private:
float x, y;
};
class Rectangle
{
public:
Rectangle(); //side1 - horizontal, side2 - vertical
void SetPoint(const Point point1, const Point point2, const Point point3, const Point point4) { LLPoint = point1; LRPoint = point2; URPoint = point3; ULPoint = point4; }
float CalcSides(Point LL, Point LR, Point UL, Point UR);
private:
Point LLPoint, LRPoint, ULPoint, URPoint;
float side1, side2, length, width, area, perimeter; //side1 - horizontal, side2 - vertical
};
float Rectangle::CalcSides(Point LL, Point LR, Point UL, Point UR)
{
side1 = (LR.x - LL.x);
}
How can I access the x and y values for the points I've created in the Rectangle class?
If you really want to do this, then you can make the classes friends.
class Rectangle;
class Point
{
friend class Rectangle;
public:
Point() { x = 0; y = 0; }
void Input(int &count); //input values
private:
float x, y;
};
More likely though, you simply want to add accessors to the Point class as it is fairly useless as is.
class Point
{
public:
Point() { x = 0; y = 0; }
void Input(int &count); //input values
float getX() const { return x; }
float getY() const { return y; }
private:
float x, y;
};
Or, if Point is really going to be so simple and not need to maintain any invariants at all, just expose x and y as public members.
Also, you probably don't want to have Point contain a Rectangle but rather refer to one either through a pointer or a reference, if it refers to one at all. After all, a Point can be useful without reference to a Rectangle (e.g. - maybe it's used for Triangles too).
I'd like to get some opinion from more experienced programmers. I have a structure like:
struct Position {
int x;
int y;
};
but I need to store for example longitude in a structure like:
struct Longitude {
int from;
int to;
};
both of them are actually the same with different names, but x and y are misleading in the case of Longitude. Would you use some typedef Position Longitude instead of defining Longitude structure (but then we have x/y there...)? Or create the same redundant structure with another names? Or maybe there are other alternatives?
I'd be inclined to keep them separate.
In C++ a struct and a class are identical constructs (excepting the default access of member variables and functions).
As your application evolves, you'll probably want to add more functions and member data to the structs. At that point the two definitions will start to diverge. Keeping them separate from the outset will assist this development.
If you're concerned about code duplication then you can always inherit from a base class or struct.
I think, if it is feasible, I would store it internally as either x/y or from/to and provide a public accessible interface for conversion.
How about this?
struct Position {
int x;
int y;
};
using Longitude = Position;
c++11 provides such sugar sintax, you have the same data with other name (you still have the same x/y stuff, but I dont really see the trouble of using them.)
I would make Position class parent of Longitude and user getters and setters instead bare attributes:
class Position {
public:
int getX() { return x; }
int getY() { return x; }
void setX(int x) { this->x = x; }
void setY(int y) { this->y = y; }
protected:
int x;
int y;
};
class Longitude : public Position {
public:
int getFrom() { return getX(); }
int getTo() { return getY(); }
void setFrom(int from) { setX(from); }
void setTo(int y) { setY(to); }
}
Before anyone says anything I know this is probably not recommended but I am still curious if there is a better way to do it or reasons not to beyond just it's a strange thing to do.
I started looking into this because I wanted to access elements of an array directly with semantically named members in the class while still being able to iterate over the array and not have to call/create some getter or setter methods.
I have a class definition that looks something like this.
class Vertex{
public:
Vertex(float x,float y,float z,float w);
float v[4];
float &x,&y,&Z,&w;
};
And a constructor that looks like this. My question is. Is there a better way of doing what I am doing in the constructor?
Vertex::Vertex(float vx,float vy,float vz,float vw):
x(*const_cast<float*>( &this->v[0] )),
y(*const_cast<float*>( &this->v[1] )),
z(*const_cast<float*>( &this->v[2] )),
w(*const_cast<float*>( &this->v[3] ))
{
v[0]=vx;
v[1]=vy;
v[2]=vz;
v[3]=vw;
}
EDIT
I'm an idiot... you can just do it like Jonathan Wakely said.
x(v[0])
I guess I had some other problems before when I tried it. Oh well.
Vertex::Vertex(float vx,float vy,float vz,float vw):
v { vx, vy, vz, vw },
x(v[0]),
y(v[1]),
z(v[2]),
w(v[3])
{
}
I'd avoid writing reference members here. The reason is that reference members prevent defaulted (compiler generated) copy/assignment special members.
class Vertex{
public:
Vertex(float x,float y,float z,float w)
: v { x, y, z, w } { }
float &x() { return v[0]; }
float &y() { return v[1]; }
float &z() { return v[2]; }
float &w() { return v[3]; }
float const &x() const { return v[0]; }
float const &y() const { return v[1]; }
float const &z() const { return v[2]; }
float const &w() const { return v[3]; }
private:
float v[4];
};
You could go this way too:
class Vertex
{
public:
float x;
float y;
float z;
float w;
Vertex(float x, float y, float z, float w);
float&
operator[](int i)
{ return *(&x + i); }
float
operator[](int i) const
{ return *(&x + i); }
};
Probably, this variant is better (compared to other alternatives) because it requires less code and gives you the additional ability to iterate over Vertex in array-style.
Personally I like #sehe's answer best but I'll give you an alternative.
struct Vector4 {
float x;
float y;
float z;
float w;
};
union VectorUnion {
Vector4 vector;
float array[4];
};
Then you can just use the VectorUnion inside your Vertex class or on its own...
I am concerned about the fact that this is a C construct and that C++ struct is slightly different (it includes the vtable etc) but I think that it should work.
Again, I think #sehe's answer is better.