Error: cannot dynamically allocate this value type object on native heap - c++-cli

I am trying to create an instance of System::DateTimeon-the-fly and assign it to System::DateTime gDate in case user uses 'P' argument. But, I get the error shown following the code snippet.
case 'P':
gDate=new DateTime(std::stoi(year), std::stoi(month), std::stoi(day));
cout << "Persian Date is: " << pDate.GetDayOfMonth(gDate) << "/" <<
pDate.GetMonth (gDate) << "/" << pDate.GetYear(gDate) << endl;
break;
Error C3255 'System::DateTime': cannot dynamically allocate this value
type object on native heap
What causes the error and how should I prevent it?
Update:
I probably should have said in the first place, I tried also the following definition:
DateTime gDate(std::stoi(year), std::stoi(month), std::stoi(day));
But, I received the error, Error C2360 initialization of 'gDate' is skipped by 'case' label

If you don't need gDate to be a pointer, and you almost certainly do not, try:
case 'P':
{
DateTime gDate(std::stoi(year), std::stoi(month), std::stoi(day));
cout << "Persian Date is: " << pDate.GetDayOfMonth(gDate) << "/" <<
pDate.GetMonth (gDate) << "/" << pDate.GetYear(gDate) << endl;
}
break;
The braces establish a scope for gDate, ensuring deletion when the program exits the braces.
CLI/CLR C++ is a different beast from C++ and has some different semantics.
CLI/C++ has added a concepts of value and ref structs and classes. These are objects with automatic lifetime control. The .Net runtime, not the programmer, decides when they live and die, and this requires different syntax.
Those tagged value are intended to be used as one would use a Plain Old Datatype like an int or a double. Create 'em as a temporary, use them, and let the stack or whatever other method of managing temporary variables is in use take care of the clean-up. You can point to them, but it is not recommended.
ref structs and classes are designed with referenced use in mind and are open game for pointers, so long as they are garbage collected pointers.
System::DateTime is a value struct, so what follows strays from its recommended use. As a pointer, System::DateTime must either be used as a garbage collected pointer with ^ in place of * and allocated with gcnew in place of new or as a variable with a defined scope.
If gDate must be a pointer, it must be defined
DateTime ^ gDate;
And allocating it requires
gDate = gcnew DateTime(std::stoi(year), std::stoi(month), std::stoi(day));
When there are no further references to this allocated object, gDate and any copies of gDate have gone out of scope, the .Net runtime's garbage collector will destroy it.

As explained here, you can create DateTime on the stack, but not on the heap.
Try like this:
DateTime gDate(std::stoi(year), std::stoi(month), std::stoi(day));
cout << "Persian Date is: " << pDate.GetDayOfMonth(gDate) << "/" <<
pDate.GetMonth (gDate) << "/" << pDate.GetYear(gDate) << endl;
break;
alternatively, you can use gcnew to allocate managed memory:
DateTime^ gDate = gcnew DateTime(std::stoi(year), std::stoi(month), std::stoi(day));

Related

Point Set Shape Detection: save planar shapes to file

Although I don't know how to write C++ I am trying to use CGAL for trying to derive building shapes from LiDAR point clouds using Point Set Shape Detection. Using the examples I can read points and normals from a file, whereupon CGAL detects shapes. The program is set to detect only planar shapes.
I would like to save the planar shapes to a file, so that I can use them in other software. But I was unable to find examples of how that can be achieved. The test program I use is based on the efficient_RANSAC_parameters.cpp code. It has a part when it iterates through all detected shapes. Could it be possible to add something there that will write the planar shapes to a file? I see the OFF format is a popular and simple way (in CGAL) to save polygons to a file, so that could be a good candidate file format.
A colleague who does know how to write C++ has helped me with this problem. He came up with the following:
while (it != shapes.end()) {
if (Plane* plane = dynamic_cast<Plane*>(it->get()))
{
std::cout << "PLANE_" << count++ << "[" << std::endl;
const std::vector<size_t> indices = it->get()->indices_of_assigned_points();
std::vector<size_t>::const_iterator iti = indices.begin();
while (iti != indices.end()) {
// Retrieves point
Point_with_normal pw = *(points.begin() + (*iti));
Kernel::Point_3 p = pw.first;
std::cout << "POINT[" << p.x() << "," << p.y() << "," << p.z() << "]" << std::endl;
// Proceeds with next point.
iti++;
}
std::cout << "]" << std::endl;
}
// Proceeds with next detected shape.
it++;
}
This block can replace loop in the efficient_RANSAC_parameters.cpp example. The output looks like this:
PLANE_0[
POINT[34.96,584.49,0.47]
POINT[34.97,585.24,0.54]
POINT[34.88,584.51,0.49]
POINT[34.98,584.75,0.49]
]
That gives me something to work with. In my case, I use sed to transform this output to SQL insert queries that allow me to transfer the data to a relational database for further processing.
In the example in the user manual you can see that once you have a plane shape object
if(Plane* plane = dynamic_cast<Plane*>(it->get())){..} you can obtain from the plane shape object a CGAL::Plane_3, from which you can obtain a point and a normal, or the coefficients of the plane.

How to output the concrete contents of a QsqlQuery before execution

For debuging prurpose I wouls like to print a sql query I am executing.
Here is my code:
QSqlQuery query;
query.prepare("INSERT INTO GeoAndEnergies VALUES(:smi,:chismi,:index,:rank,:comp,:met,:ba,:nha, :na, :gr, :gconv, :scfconv, :ener,:chemf,:prog,:ver,:cha,:mult,:sol,:geo, :freq, :enth, :free_e, :wei)");;
query.bindValue(":smi",QVariant(SMILES));
query.bindValue(":chismi",QVariant(ChiralSMILES));
query.bindValue(":index",QVariant(IndexCS));
query.bindValue(":rank",QVariant(Confrank));
query.bindValue(":comp",QVariant(Comptype));
query.bindValue(":met",QVariant(Method));
query.bindValue(":ba",QVariant(BASE));
query.bindValue(":nha",QVariant(NheavyAtom));
query.bindValue(":na",QVariant(NAtoms));
query.bindValue(":gr",QVariant(Grid));
query.bindValue(":gconv",QVariant(GeoConvergence));
query.bindValue(":scfconv",QVariant(SCFConvergence));
query.bindValue(":ener",QVariant(Energy));
query.bindValue(":chemf",QVariant(ChemicalFormula));
query.bindValue(":prog",QVariant(SOFTWARE));
query.bindValue(":ver",QVariant(VERSION));
query.bindValue(":cha",QVariant(Charge));
query.bindValue(":mult",QVariant(Multiplicity));
query.bindValue(":sol",QVariant(SOLVANT));
query.bindValue(":geo",QVariant(Geometry));
query.bindValue(":freq",QVariant(freq));
query.bindValue(":enth",QVariant(enthalpy));
query.bindValue(":free_e",QVariant(free_enthalpy));
query.bindValue(":wei",QVariant(weight));
if (!query.exec()){
std::cout << "Une erreur s'est produite. :(" << std::endl << q2c(query.lastError().text()) << std::endl;
}
return;
Thanks for tips.
query.executedQuery() will return the text of the last query that was successfully executed, with placeholder values replaced with concrete values. Hopefully, it'll also work if there was an error due to bad values, etc.
Note also that the explicit QVariant constructions are never necessary. For types that are handled by QVariant, the conversion will be done automatically. For custom types, there's no QVariant constructor available and the code won't compile anyway. You'd need to use QVariant::fromValue(xyz), where xyz has a custom type that has been Q_DECL_METATYPE'd in the header where the type is declared.
Your code could be rewritten as follows:
QSqlQuery query;
query.prepare("INSERT INTO GeoAndEnergies VALUES(:smi,:chismi,:index,:rank,:comp,:met,:ba,:nha, :na, :gr, :gconv, :scfconv,"
":ener,:chemf,:prog,:ver,:cha,:mult,:sol,:geo, :freq, :enth, :free_e, :wei)");
query.bindValue(":smi", SMILES);
query.bindValue(":chismi", ChiralSMILES);
query.bindValue(":index", IndexCS);
query.bindValue(":rank", Confrank);
query.bindValue(":comp", Comptype);
query.bindValue(":met", Method);
query.bindValue(":ba", BASE);
query.bindValue(":nha", NheavyAtom);
query.bindValue(":na", NAtoms);
query.bindValue(":gr", Grid);
query.bindValue(":gconv", GeoConvergence);
query.bindValue(":scfconv", SCFConvergence);
query.bindValue(":ener", Energy);
query.bindValue(":chemf", ChemicalFormula);
query.bindValue(":prog", SOFTWARE);
query.bindValue(":ver", VERSION);
query.bindValue(":cha", Charge);
query.bindValue(":mult", Multiplicity);
query.bindValue(":sol", SOLVANT);
query.bindValue(":geo", Geometry);
query.bindValue(":freq", freq);
query.bindValue(":enth", enthalpy);
query.bindValue(":free_e", free_enthalpy);
query.bindValue(":wei", weight);
if (!query.exec()) {
qWarning() << "The query has failed:" << query.executedQuery();
}

YAML ofstream emitter

I find this example:
ofstream ofstr("output.yaml");
YAML::Emitter out(ofstr);
out << some_large_document;
// not necessary anymore:
// ofstr << out.c_str()
But when i try use it, i have:
D:\work\C\map.cpp||In function `int main()':|
D:\work\C\map.cpp|24|error: no matching function for call to `YAML::Emitter::Emitter(std::ofstream&)'|
D:\work\C\yaml-cpp\emitter.h|23|note: candidates are: YAML::Emitter::Emitter(YAML::Emitter&)|
D:\work\C\yaml-cpp\emitter.h|25|note: YAML::Emitter::Emitter()|
||=== Build finished: 1 errors, 0 warnings ===|
There's no constructor to YAML::Emitter that takes a stream. (Where did you find that example?)
Instead, you do need to use the commented out line:
ofstream ofstr("output.yaml");
YAML::Emitter out;
out << some_large_document;
ofstr << out.c_str(); // is necessary!

What is the difference of declaration of a variable in a loop and before the loop?

Look at this example:
int i;
for (i=1;i.......
and this:
for (int i=1;i........
What's the difference between them?
The first one declares the variable in the scope outside of the loop; after the loop has ended, the variable will still exist and be usable. The second one declares the variable such that it belongs to the scope of the loop; after the loop, the variable ceases to exist, preventing the variable from being inadvertantly/mistakenly used.
In C99, C++, Java, and other similar languages, you will find mostly the second syntax as it is safer -- the loop index belongs to the loop and isn't modified / shared elsewhere. However, you will see a lot of the former in older C code, as ANSI C did not allow the loop variable to be declared in the loop like that.
To give an example:
int i;
// ... lots of stuff
for ( i = 0; i < 5; i++ ){
printf("%d\n",i); // can access i; prints value of i
}
printf("%d\n",i); // can access i; prints 5
By contrast:
for (int i = 0; i < 5; i++ ){
std::cout << i << std::endl; // can access i; prints value of i
}
std::cout << i << std::endl; // compiler error... i not in this scope
That would depend on the language, which you haven't specified :-)
In C (and some others), the scope (effectively duration in this case) of the variable is different. In the first, the variable exists after the loop because it's declared outside it.
In the latter, it disappears when the loop ends because its existence is "inside" the loop body.

AbsoluteToNanoseconds vs AbsoluteToDuration

Apple has extremely comprehensive documentation, but I can't find any documentation for the function AbsoluteToNanoseconds? I was to find the difference between AbsoluteToNanoseconds and AbsoluteToDuration.
Note
I am beginning to think that the Apple Docs only cover Objective-C functions? Is this the case?
I found the following by using Apple-double-click:
Duration 32-bit millisecond timer for drivers
AbsoluteTime 64-bit clock
I'm not sure why it isn't documented anywhere, but here is an example of how it is used, if that helps:
static float HowLong(
AbsoluteTime endTime,
AbsoluteTime bgnTime
)
{
AbsoluteTime absTime;
Nanoseconds nanosec;
absTime = SubAbsoluteFromAbsolute(endTime, bgnTime);
nanosec = AbsoluteToNanoseconds(absTime);
return (float) UnsignedWideToUInt64( nanosec ) / 1000.0;
}
UPDATE:
"The main reason I am interested in the docs is to find out how it differs from AbsoluteToDuration"
That's easier. AbsoluteToNanoseconds() returns a value of type Nanoseconds, which is really an UnsignedWide struct.
struct UnsignedWide {
UInt32 hi;
UInt32 lo;
};
In contrast, AbsoluteToDuration() returns a value of type Duration, which is actually an SInt32 or signed long:
typedef SInt32 Duration;
Durations use a smaller, signed type because they are intended to hold relative times. Nanoseconds, on the other hand, only make sense as positive values, and they can be very large, since computers can stay running for years at a time.
According to https://developer.apple.com/library/prerelease/mac/releasenotes/General/APIDiffsMacOSX10_9/Kernel.html,
SubAbsoluteFromAbsolute(), along with apparently all the other *Absolute* functions, have been removed from Mavericks. I have confirmed this.
These functions are no longer necessary since at least in Mavericks and Mountain Lion (the two I tested), mach_absolute_time() already returns time in nanoseconds, and not in absolute form (which used to be the number of bus cycles), making a conversion no longer necessary. Thus, the conversion shown in clock_gettime alternative in Mac OS X and similar code presented in several places on the web, is no longer necessary. This can be confirmed on your system by checking that both the numerator and denominator returned by mach_timebase_info() are 1.
Here is my test code with lots of output to check if you need to do the conversion on your system (I have to perform a check since my code might run on older Macs, although I do the check at program initiation and set a function pointer to call a different routine):
#include <CoreServices/CoreServices.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <time.h>
#include <iostream>
using namespace std;
int main()
{
uint64_t now, then;
uint64_t abs, nano;
mach_timebase_info_data_t timebase_info = {0,0};
then = mach_absolute_time();
sleep(1);
now = mach_absolute_time();
abs = now - then;
mach_timebase_info(&timebase_info);
cout << "numerator " << timebase_info.numer << " denominator "
<< timebase_info.denom << endl;
if ((timebase_info.numer != 1) || (timebase_info.denom != 1))
{
nano = (abs * timebase_info.numer) / timebase_info.denom;
cout << "Have a real conversion value" << endl;
}
else
{
nano = abs;
cout << "Both numerator and denominator are 1" << endl;
}
cout << "milliseconds = " << nano/1000000LL << endl;
}