I have the below structures in my C++ code.
struct XYZ {
double x;
double y;
double z;
};
struct Data {
XYZ xyz_point;
double item_1;
double item_2;
double item_3;
};
In my code I create a vector of structure Data.
std::vector<Data> data_vector;
for (i = 0; i < 5; i++) {
Data data_point_1;
data_point_1.xyz_point.x = 10.0;
data_point_1.xyz_point.y = 11.0;
data_point_1.xyz_point.z = 12.0;
data_point_1.item_1 = 13.0;
data_point_1.item_2 = 14.0;
data_point_1.item_3 = 15.0;
data_vector.push_back(data_point_1);
}
Code build successful without any errors, however during the CPP_Check I get the below warnings/error. data_point_1 does not have the field x, y and z.
[test.cc:122]: (error: uninitStructMember) Uninitialized struct member: data_point_1.x
[test.cc:122]: (error: uninitStructMember) Uninitialized struct member: data_point_1.y
[test.cc:122]: (error: uninitStructMember) Uninitialized struct member: data_point_1.z
Could you please help me to resolve this.
Thank you,
push_back requires a default constructor. The compiler is able to supply that, but it doesn't initialise the doubles.
CPP_Check is spotting that.
One fix is to use emplace_back instead with the initialiser-list syntax. That doesn't require a default constructor. Another option is to supply a default constructor that initialises the members.
Related
Is there a syntax to initialize DataItem dh.size element to sizeof(DataItem)? The code below uses constructor and relying on compiler to optimize things to constant values. Not the perfect solution... Is there a syntax to initialize nested structs?
struct DataHeader_t {
int sz = 0;
int type = 0;
};
struct DataItem {
DataItem() {dh.sz = sizeof(DataItem);}
DataHeader_t dh;
float data1 = 0;
float data2 = 0;
...
};
Not the perfect solution... Is there a syntax to initialize nested structs?
Yes, that structure is called constructor, and you're already using it.
I have the following base calibration struct:
struct Standard
{
public:
unsigned long ulCamID;
std::string sCalibrationModel;
float fC;
float fXh;
float fYh;
Standard()
{
ulCamID = 0;
fC = fXh = fYh = 0.0;
}
virtual ~Standard()
{
}
};
And derived structs such as:
struct Aus: public Standard
{
public:
float fK1;
float fK2;
float fK3;
float fP1;
float fP2;
float fB1;
float fB2;
Aus()
{
fC = fXh = fYh = fK1 = fK2 = fK3 = fP1 = fP2 = fB1 = fB2 = 0.0;
}
};
Because I do not know at compile how many Calibrations I will need, nor which calibration models, I thought it convenient to put it into a std::vector and use boost::shared_ptr to point to them. I do this like so:
typedef boost::shared_ptr<CalibrationModels::Standard> shr_ptr;
std::vector<shr_ptr> vec;
shr_ptr p(new CalibrationModels::Aus);
vec.push_back(p);
p.reset(new CalibrationModels::Brown);
vec.push_back(p);
This seems to work fine (the debugger reports that the pointers inside the vector point to the derived struct). However, I have difficulties now to access/change the values inside the vector. If I try something like this:
boost::dynamic_pointer_cast<CalibrationModels::Aus>(vec.at(0)).px->fK3 = 1.3221e-9
It tells me that px is private ( ‘boost::shared_ptr::element_type* boost::shared_ptr::px’ is private element_type * px; ).
What is the proper way to access and manipulate the values inside those pointers to derived structs?
The problem you have is that px is a private member of the smart pointer. To access your class boost provides the -> operator. You can use that to access the pointer as you would use it for a regular pointer. This would change your line to this:
boost::dynamic_pointer_cast<CalibrationModels::Aus>(vec.at(0))->fK3 = 1.3221e-9;
^^ Difference here
Note that, if you actually need the value, you can use the get() method to get the pointer that is stored in the shared_ptr.
I have this definition for my structure:
struct localframevelo
{
double ivelo; //i(x) component of velocity
double cvelo; //c(y) component of velocity
double rvelo; //r(z) component of velocity
double speed; //total magnitude of velocity
localframevelo()
{
ivelo = 0;
cvelo = 0;
rvelo = 0;
speed = 0;
}
localframevelo(double init_ivelo, double init_cvelo, double init_rvelo)
{
ivelo = init_ivelo;
cvelo = init_cvelo;
rvelo = init_rvelo;
speed = sqrt(pow(ivelo, 2.0) + pow(cvelo, 2.0) + pow(rvelo, 2.0));
}
};
Here is a class that I am trying to use the default constructor of localframevelo in:
class missionprofile
{
//misison waypoints structure************************
private:
double stdholdtime; // 0.25 second within tolerance radius to "reach" a waypoint
double stdtolrad; // 0.5 meter tolerance radius (error magnitude) to "be at" a waypoint
localframevelo stdvelo;
waypoint missionwaypoints[MAXLISTLENGTH];
int numwaypoints;
public:
missionprofile();
missionprofile(int points, double StdHoldTime, double StdTolRadius, localframevelo StdVelo);
};
Here is the implementation of the default constructor for the class that I am trying to call the localframevelo's default constructor:
missionprofile::missionprofile()
{
numwaypoints = 0;
stdholdtime = 0;
stdtolrad = 0;
stdvelo(); //ERROR
}
I get this error: call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type. I am using the mbed compiler, what is wrong with my code?
You can safely remove this line:
stdvelo();
In the context of a function body, this is interpreted as a call to the operator()() of an instance of localframevelo, not an initialization. The data member will be default constructed anyway without any explicit initialization. But what you should really be doing is to initialize your data members in the constructor's initialization list:
missionprofile::missionprofile()
: numwaypoints(),
stdholdtime(),
stdtolrad(),
stdvelo()
{
}
And similarly for localframevelo's constructors and the other missionprofile constructor.
When you write stdvelo(), the compiler sees stdvelo.operator()() and then complains when no such function exists.
The data member is going to be constructed anyway; you don't need the line at all.
Also, it's marginally faster to use initialization rather than assignment for your starting values (though chances are high that your compiler will optimize away the difference anyway).
So you'd use this, for example, for the second constructor:
localframevelo(double init_ivelo, double init_cvelo, double init_rvelo)
: ivelo(init_velo)
, cvelo(init_cvelo)
, rvelo(init_rvelo)
, speed(sqrt(pow(ivelo, 2.0) + pow(cvelo, 2.0) + pow(rvelo, 2.0)))
{}
For the first, you'd just use 0 instead of init_velo et al.
I have a class CS which is to represent the co-ordinate system in 3D i.e.(x, y, z)
class CS
{
private:
double x;
double y;
double z;
}
CS::CS()
{
x = NULL;//this causes x = 0//i want the address of x to be 0x000000 & not x = 0
y = NULL;
z = NULL:
}
I want that the user can create a CS (0, 0, 0).
In the constructor i want to initialise the address of x, y & z to NULL.
this is to differentiate between the user defined (0, 0, 0) & the default value.
I am creating the objects of CS dynamically, so there is no point in using the following code:
class CS
{
private:
double *x;
double *y;
double *z;
}
CS:CS()
{
x = new double;
x = NULL;
//same for y & z
}
Primarily, i want to manually assign 0x000000 address to any variable(int or double or char) without using pointers.
any suggestions?
You can't change the positions of x,y,and z to be NULL, since there positions will always be offsets from the CS object. They will always exist. It's not that CS has an x like you have a car, it's like CS has an x like you have a head. You can't not have a head. If they were integers, you would have to make them pointers (like you said you didn't want to do), because that would be the only way to tell uninitialized from initialized. However, doubles have a magic value that is rarely used:
CS:CS()
: x(std::numeric_limits<double>::quiet_NaN())
: y(std::numeric_limits<double>::quiet_NaN())
: z(std::numeric_limits<double>::quiet_NaN())
{ }
Users probably won't be setting x, y, and z to (NOT A NUMBER) intentially.
Primarily, i want to manually assign 0x000000 address to any variable(int or double or char) without using pointers. any suggestions?
That's not what you want. What you want is the ability to detect whether a variable has been set or not.
Others have suggested things like using a specific floating-point value to detect the uninitialized state, but I suggest employing Boost.Optional. Consider:
class CS
{
private:
boost::optional<double> x;
boost::optional<double> y;
boost::optional<double> z;
}
boost::optional either stores the type you give to the template parameter or it stores nothing. You can test the difference with a simple boolean test:
if(x)
{
//Has data
}
else
{
//Has not been initialized
}
The downside is that accessing the data is a bit more complex:
x = 5.0; //Initialize the value. x now has data.
y = 4.0 * x; //Fails. x is not a double; it is an optional<double>.
y = 4.0 * (*x); //Compiles, but only works at runtime if x has a value.
You have several options:
Use pointers.
Use a boolean flag alongside each variable indicating whether the variable has been set.
If the range of allowable values is limited, you could use a special value to stand for "not set". For double, a not-a-number is often a natural candidate. For int and char it's often more tricky to pick a good value.
None of these options is indisputably better than the other two as they involve different tradeoffs. Take your pick.
Why can't you simply do this:
class CS
{
public:
// Constructs a CS initialized to 0, 0, 0
CS() : x(0), y(0), z(0), is_initialized(false) {}
// User defined values
CS(double newX, double newY, double newZ) : x(newX), y(newY), z(newZ), is_initialized(true) {}
private:
double x;
double y;
double z;
// If you need to know that this was initialized a certain way, you could use this suggestion from the comments:
bool is_initialized;
}
If I understand correctly, you want to be able to tell the difference between an invalid, default constructed CS and a valid one with values (0.0, 0.0, 0.0). This is exactly what boost::optional http://www.boost.org/doc/libs/1_47_0/libs/optional/doc/html/index.html is for.
You can't really represent it in the same number of bits without having a sentinel. If 0 is a valid number, then you can't use it. If you try and foist null handling into a value type you will have fundamentally incorrect and unmaintainable code.
When handling nulls properly you would expect to see an interface like this:
struct foo {
virtual ~foo() {}
virtual bool getX(double &val) = 0;
virtual bool getY(double &val) = 0;
virtual bool getZ(double &val) = 0;
};
The implementation can have a flag that it checks before access.
void some_func(foo *f) {
double x, y, z;
if (f->getX(x) && f->getY(y) && f->getZ(z)) {
cout << x << ", " << y << ", " << z << endl;
} else {
throw std::logic_error("expected some values here");
}
}
You don't want to use an invalid value and not know it. Having to check the return values is tedious obviously, but it gives you the most control. You could also have helpers or overloads that would throw if they weren't valid.
struct bar {
double getX() {
if (!valid)
throw std::logic_error("bar is not valid");
return x;
}
bool valid;
double x, y, z;
}
For me, the difference between foo and bar is that low level code handling the data shouldn't enforce a policy of whether the data is there or not. At higher levels of abstraction you can and should have expectations of whether the data should valid when you go to use it. The both can exist in a system, but foo is necessary.
One way to get the semantics of what you want would be to have the datatype of the coordinates be a type that carries with it a value indicating whether it has been assigned. Something like this.
template<typename T>
class CoordinateValue {
public:
CoordinateValue() : uninitialized(true), val(0) {}
CoordinateValue(T x) : uninitialized(false), val(x) {}
void setVal(T x) {val = x; uninitialized= false}
// Trivial getters
private:
T val;
bool uninitialized;
};
I'd prefer something like this over cuter methods unless memory is really scarce for some reason.
If the coordinates are either all default or all set, then you can have a single flag rather than a coordinate datatype that includes the flag.
I want that the user can create a CS (0, 0, 0). In the constructor i
want to initialise the address of x, y & z to NULL. this is to
differentiate between the user defined (0, 0, 0) & the default value.
I am creating the objects of CS dynamically, so there is no point in
using the following code:
This is the problem. Firstly, default value? What default value? Why should there be a default value? That's wrong. And secondly, it's fundamentally impossible for you to change the address of any variable.
What you want cannot be done and even if it could, it would be a horrendously bad idea.
You can't change the address of a variable. And you can't assign pointer values (like NULL, or nullptr in C++) to a variable of a non-pointer type, such as double.
Is there a better way to initialise C structures in C++ code?
I can use initialiser lists at the variable declaration point; however, this isn't that useful if all arguments are not known at compile time, or if I'm not declaring a local/global instance, eg:
Legacy C code which declares the struct, and also has API's using it
typedef struct
{
int x, y, z;
} MyStruct;
C++ code using the C library
void doSomething(std::vector<MyStruct> &items)
{
items.push_back(MyStruct(5,rand()%100,items.size()));//doesn't work because there is no such constructor
items.push_back({5,rand()%100,items.size()});//not allowed either
//works, but much more to write...
MyStruct v;
v.x = 5;
v.y = rand()%100;
v.z = items.size();
items.push_back(v);
}
Creating local instances and then setting each member one at a time (myStruct.x = 5; etc) is a real pain, and somewhat hard to read when trying to add say 20 different items to the container...
If you can't add a constructor (which is the best solution in C++03 but you probably have compatibility constraint with C), you can write a function with the same effect:
MyStruct makeAMyStruct(int x, int y, int z)
{
MyStruct result = { x, y, z };
return result;
}
items.push_back(makeAMyStruct(5,rand()%100,items.size()));
Edit: I'd have checked now that C++0X offers something for this precise problem:
items.push_back(MyStruct{5,rand()%100,items.size()});
which is available in g++ 4.4.
You're looking for C99 compound literals. Example code:
struct foo *foo = malloc(sizeof *foo);
*foo = (struct foo){ bar, baz };
How about:
MyStruct v = {5, rand()%100, items.size()};
items.push_back(v);
Create a function to initialize it, similar to what a C++ constructor would do.
Not clear what you are asking. In C++, the obvious solution is to give the struct a constructor:
struct MyStruct {
int x, y, z;
MyStruct( int ax, int ay, int az ) : x( ax ), y( ay ), z( az ) {}
};
Another option is to derive from the struct and add a constructor there.
struct MyDerivedStruct : public MyStruct
{
MyDerivedStruct(int xi, int yi, int zi)
{
x = xi;
y = yi;
z = zi;
}
}
Then you can use this derived type in your own code and pass it to the C library when necessary. The language should take care of implicitly converting to MyStruct when appropriate.
As a bonus, you could also add other useful member functions, perhaps even wrapping many of the legacy C functions that use this type.