question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,681,564 | 1,681,670 | c++ problem with build | I have this method declaration in Util.h file
30:string to_string(const bit_vector& v);
Util.cc file has the definition
string to_string(const bit_vector& v){
string str = "";
for (bit_vector::const_iterator i = v.begin(); i < v.end(); ++i){
if(*i == 1) str += "1";
else str += "0";
}
return str;
}
when I try to build the project it says that in line 30
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2143: syntax error : missing ',' before '&'
Im using visual studio 2008, Can some one help me to get out of these two errors! Dont know whether there is a problem with bit_vector !!! any ideas???
| It seems bit_vector is not defined. There are claims that it should be included in <vector>, but that doesn't seem to be the case on Visual Studio 2008. Try
typedef vector<bool> bit_vector;
before the first usage of bit_vector.
|
1,681,637 | 1,690,991 | COleDataSource/COleDropTarget cancel drag&drop operation | I have implemented my custom drag&drop by deriving from COleDataSource and COleDropTarget. Everythings work fine but I have an scenario that makes the application crashes.
That happens when the dialog where the drag&drop controls are placed is destroyed while the user is in the middle of a drag&drop operation.
This is not usual because normally to close a dialog the user have to use the mouse or the keyboard and then the drag&drop operation is automatically canceled. But in this scenario the dialog can be closed due to an external condition (a custom message that changes the view) and then the drap&drop operation is not canceled.
So my question is, how can I programmatically cancel the drag&drop operation?
The operation is started from the OnLButtonDown message handle calling COleDataSource::DoDragDrop.
Update:
I've implemented using DelayRender and it continues crashing. These are the two asserts I am getting:
When the mouse pointer (while dragging) is inside a control that is a COleDropTarget-derived class.
alt text http://www.freeimagehosting.net/uploads/b34a62c5ac.jpg
The assert is in the Revoke method and this is the line:
ASSERT(m_lpDataObject == NULL);
When the mouse pointer is not inside a COleDropTarget-derived class.
alt text http://www.freeimagehosting.net/uploads/a0e8298490.jpg
In this case the assert is in the destruction of the COleDataSource (in fact it is in its parent class CCmdTarget). In this line:
ASSERT(m_dwRef <= 1);
Thanks in advance!
| I'm not sure if this would work but you could try overriding the QueryContinueDrag method of the COleDropTarget instance and returning DRAGDROP_S_CANCEL in the case where the dialog has been closed
|
1,681,677 | 1,681,742 | MSBuild / Visual Studio distributed builds | I develop / maintain an application that takes a long time to build (as in, a full build takes in excess of six hours!). After having spent most of the day building our application I've started looking into ways of improving build time. The suggestions on this Stack Overflow question were:
Fixing compile warnings
Unity builds (for developers)
Distributed builds
I'd like to know more about how to do the third option (distributed builds) for a MSBuild / Visual Studio build system.
| Go have a look at http://www.xoreax.com/ for Incredibuild.
It is not free, but we use it and it's pretty impressive. It is well integrated into Visual Studio and extremely simple to use. You can run into a problem every now and then, but it's definitely worth a look.
Once it's installed, in Visual Studio, the principle is to use the "Build solution with Incredibuild" menu entry instead of the "build solution" one. All needed files are transparently transferred to distant computers and output files are downloaded back.
|
1,681,748 | 1,688,417 | Oracle 7 ProC++ pre-compiled code | I am modifying an old DLL which uses Oracle 7 ProC++ precompiled code (SQLLIB18.LIB) and don't have any documentation for this release. No joy back from Oracle either.
Does anyone know what the numbers in the following compilation unit data represent?
static const short sqlcud0[] = {8,4130,2,0,0,1,189,0,6,49,0,11,11,0,2,7,68,66,95,78,65,77,69,3,97,0,0,3,5,0,0,3,97,0,0,3,97,0,0,3,97,0,0,3,3,0,0,3,5,0,0,3,5,0,0,3,5,0,0,3,97,0,0,};
| Unfortunately, I believe this is code produced by the Oracle ProC precompiler, and is not likely to be documented for the general public, even if you have the entire set of manuals. I did find a link to V7.3.4 documentation on Oracle's website. I don't suppose you still have the original ProC source code?
|
1,681,900 | 1,682,492 | OpenMP: Causes for heap corruption, anyone? | EDIT: I can run the same program twice, simultaneously without any problem - how can I duplicate this with OpenMP or with some other method?
This is the basic framework of the problem.
//Defined elsewhere
class SomeClass
{
public:
void Function()
{
// Allocate some memory
float *Data;
Data = new float[1024];
// Declare a struct which will be used by functions defined in the DLL
SomeStruct Obj;
Obj = MemAllocFunctionInDLL(Obj);
// Call it
FunctionDefinedInDLL(Data,Obj);
// Clean up
MemDeallocFunctionInDLL(Obj);
delete [] Data;
}
}
void Bar()
{
#pragma omp parallel for
for(int j = 0;j<10;++j)
{
SomeClass X;
X.Function();
}
}
I've verified that when some memory is attempted to be deallocated through MemDeallocFunctionInDLL(), the _CrtIsValidHeapPointer() assertion fails.
Is this because both threads are writing to the same memory?
So to fix this, I thought I'd make SomeClass private (this is totally alien to me, so any help is appreciated).
void Bar()
{
SomeClass X;
#pragma omp parallel for default(shared) private(X)
for(int j = 0;j<10;++j)
{
X.Function();
}
}
And now it fails when it tries to allocate memory in the beginning for Data.
Note: I can make changes to the DLL if required
Note: It runs perfectly without #pragma omp parallel for
EDIT: Now Bar looks like this:
void Bar()
{
int j
#pragma omp parallel for default(none) private(j)
for(j = 0;j<10;++j)
{
SomeClass X;
X.Function();
}
}
Still no luck.
| Check out MemAllocFunctionInDLL, FunctionDefinedInDLL, MemDeallocFunctionInDLL are thread-safe, or re-entrant. In other words, do these functions static variables or shared variables? In such case, you need to make it sure these variables are not corrupted by other threads.
The fact without omp-for is fine could mean you didn't correctly write some functions to be thread-safe.
I'd like to see what kind of memory allocation/free functions has been used in Mem(Alloc|Dealloc)FunctionInDLL.
Added: I'm pretty sure your functions in DLL is not thread-safe. You can run this program concurrently without problem. Yes, it should be okay unless your program uses system-wide shared resources (such as global memory or shared memory among processes), which is very rare. In this case, no shared variables in threads, so your program works fine.
But, invoking these functions in mutithreads (that means in a single process) crashes your program. It means there are some shared variables among threads, and it could have been corrupted.
It's not a problem of OpenMP, but just a multithreading bug. It could be simple to solve this problem. Please take a look the DLL functions whether they are safe to be called in concurrent by many threads.
How to privatize static variables
Say that we have such global variables:
static int g_data;
static int* g_vector = new int[100];
Privatization is nothing but a creating private copy for each thread.
int g_data[num_threads];
int* g_vector[num_threads];
for (int i = 0; i < num_threads; ++i)
g_vector[i] = new int[100];
And, then any references on such variables are
// Thread: tid
g_data[tid] = ...
.. = g_vector[tid][..]
Yes, it's pretty simple. However, this sort of code may have a false sharing problem. But, false sharing is a matter of performance, not correctness.
First, just try to privatize any static and global variables. Then, check it correctness. Next, see the speedup you would get. If the speedup is scalable (say 3.7x faster on quad core), then it's okay. But, in case of low speedup (such as 2x speedup on quad core), then you probably look at the false sharing problem. To solve false sharing problem, all you need to do is just putting some padding in data structures.
|
1,681,903 | 1,698,474 | Submitting QSqlRecord to MySQL database in Qt | I want to access a MySQL database and I want to read+write data from+to the database within my Qt/C++ program. For the read write process, I try to use QSqlTableModel, QSqlTableRcord and QSqlDatabase as this is a very pleasant approach without too much of SQL commands which I dislike for the one or other reason (to handle myself).
I got a similar approach already running (so the database is running already) but it is cluttered all over.
So the simple question is what am I doing wrong within these few lines of example code:
Using QT 4.5.x
The test database has 3 columns: float x, float y, blob img
int main(){
QImage img("./some_image.png");
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("test");
db.setPort(3306);
db.setUserName("root");
db.setPassword("xxxxxxx");
if (!db.open() )
qDebug("Mising db / unable to open");
else {
QSqlTableModel model;
qDebug() << "tables::" <<db.tables(); //so I see the table exists and gets detected
model.setTable("test_table");
QSqlRecord rec;
rec.setValue(0,1.0f);
rec.setValue(1,2.0f);
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
img.save(&buffer, "PNG");
rec.setValue(2,ba);
model.insertRecord(0,rec);
qDebug() << model.lastError().text();
if (!model.submitAll())
qDebug() << "Submit all did not work";
return 0;
}
Thx for any help, I already run from one end of the Qt docs to the other but did not find a solution and I already wasted 5 hours doing that, so I am thankful for any hint (unless you suggest to do it completely different).
| Your QSqlRecord doesn't have any fields defined. You need to add
rec.append(QSqlField("x", QVariant::Double));
rec.append(QSqlField("y", QVariant::Double));
rec.append(QSqlField("img", QVariant::Image));
before you set the values
|
1,681,964 | 1,682,019 | Explicit Address Manipulation in C++ | Please check out the following func and its output
void main()
{
Distance d1;
d1.setFeet(256);
d1.setInches(2.2);
char *p=(char *)&d1;
*p=1;
cout<< d1.getFeet()<< " "<< d1.getInches()<< endl;
}
The class Distance gets its values thru setFeet and setInches, passing int and float arguments respectively. It displays the values through through the getFeet and getInches methods.
However, the output of this function is 257 2.2. Why am I getting these values?
| This is a really bad idea:
char *p=(char *)&d1;
*p=1;
Your code should never make assumptions about the internal structure of the class. If your class had any virtual functions, for example, that code would cause a crash when you called them.
I can only conclude that your Distance class looks like this:
class Distance {
short feet;
float inches;
public:
void setFeet(...
};
When you setFeet(256), it sets the high byte (MSB) to 1 (256 = 1 * 2^8) and the low byte (LSB) to 0. When you assign the value 1 to the char at the address of the Distance object, you're forcing the first byte of the short representing feet to 1. On a little-endian machine, the low byte is at the lower address, so you end up with a short with both bytes set to 1, which is 1 * 2^8 + 1 = 257.
On a big-endian machine, you would still have the value 256, but it would be purely coincidental because you happen to be forcing a value of 1 on a byte that would already be 1.
However, because you're using undefined behavior, depending on the compiler and the compile options, you might end up with literally anything. A famous expression from comp.lang.c is that such undefined behavior could "cause demons to fly out of your nose".
|
1,682,844 | 1,682,885 | Templates: template function not playing well with class's template member function | This is a minimal test case of some code that I actually have. It fails when it tries to evaluate a.getResult<B>():
test.cpp: In function 'void printStuff(const A&)':
test.cpp:6: error: expected primary-expression before '>' token
test.cpp:6: error: expected primary-expression before ')' token
The code is:
#include <iostream>
template< class A, class B>
void printStuff( const A& a)
{
size_t value = a.getResult<B>();
std::cout << value << std::endl;
}
struct Firstclass {
template< class X >
size_t getResult() const {
X someInstance;
return sizeof(someInstance);
}
};
int main(int, char**) {
Firstclass foo;
printStuff<Firstclass, short int>(foo);
printStuff<Firstclass, double>(foo);
std::cout << foo.getResult< double >() << std::endl;
return 0;
}
If I comment out the printStuff function and where it's called, the foo.getResult< double >() call compiles fine and does what is expected.
Any idea what's going on? I've been working with extensively templated code for a while and have never encountered anything like this.
| When you refer to a template that is a member of dependent type, you have to prepend it with a keyword template. This is how the call to getResult inside printStuff should look
size_t value = a.template getResult<B>();
This is similar to using the keyword typename when referring to nested typenames in a dependent type. For some reason, the bit about typename with nested types is rather well-known, but the similar requirement for template with nested templates is relatively unknown.
Note that the general syntax structure is a bit different though. The typename is always put in front of the full name of the type, while template is inserted in the middle.
Again, this is only necessary when you are accessing a template member of a dependent type, which in the above example would be A in printStuff. When you call foo.getResult<> in main the type of foo is not dependent, so there's no need to include the template keyword.
|
1,683,051 | 1,683,917 | FILE * and istream: connect the two? | Suppose I "popen" an executable, I get a FILE* in return. Furthermore, suppose I'd like to "connect" this file to an istream object for easier processing, is there a way to do this?
| There is no standard way but if you want a quick solution you can get the file descriptor with fileno() and then use Josuttis' fdstream. There may be similar efforts around but I used this in the distant past and it worked fine. If nothing else it should be a very good map to implementing your own.
|
1,683,081 | 1,844,929 | What's the most efficient way to do recursive XPath queries using libxml2? | I've written a C++ wrapper function for libxml2 that makes it easy for me to do queries on an XML document:
bool XPathQuery(
const std::string& doc,
const std::string& query,
XPathResults& results);
But I have a problem: I need to be able to do another XPath query on the results of my first query.
Currently I do this by storing the entire subdocument in my XPathResult object, and then I pass XPathResult.subdoc into the XPathQuery function. This is awfully inefficient.
So I'm wondering ... does libxml2 provide anything that would make it easy to store the context of an xpath query (a reference to a node, perhaps?) and then perform another query using that reference as the xpath root?
| You should reuse the xmlXPathContext and just change its node member.
#include <stdio.h>
#include <libxml/xpath.h>
#include <libxml/xmlerror.h>
static xmlChar buffer[] =
"<?xml version=\"1.0\"?>\n<foo><bar><baz/></bar></foo>\n";
int
main()
{
const char *expr = "/foo";
xmlDocPtr document = xmlReadDoc(buffer,NULL,NULL,XML_PARSE_COMPACT);
xmlXPathContextPtr ctx = xmlXPathNewContext(document);
//ctx->node = xmlDocGetRootElement(document);
xmlXPathCompExprPtr p = xmlXPathCtxtCompile(ctx, (xmlChar *)expr);
xmlXPathObjectPtr res = xmlXPathCompiledEval(p, ctx);
if (XPATH_NODESET != res->type)
return 1;
fprintf(stderr, "Got object from first query:\n");
xmlXPathDebugDumpObject(stdout, res, 0);
xmlNodeSetPtr ns = res->nodesetval;
if (!ns->nodeNr)
return 1;
ctx->node = ns->nodeTab[0];
xmlXPathFreeObject(res);
expr = "bar/baz";
p = xmlXPathCtxtCompile(ctx, (xmlChar *)expr);
res = xmlXPathCompiledEval(p, ctx);
if (XPATH_NODESET != res->type)
return 1;
ns = res->nodesetval;
if (!ns->nodeNr)
return 1;
fprintf(stderr, "Got object from second query:\n");
xmlXPathDebugDumpObject(stdout, res, 0);
xmlXPathFreeContext(ctx);
return 0;
}
|
1,683,162 | 1,683,233 | Best way to port MFC COM Server to Managed code | I am working on an application suite comprising of multiple Automation servers written using MFC and this is legacy code. These apps inter communicate via COM interfaces and other events. Most of these apps provide multiple form views with various input controls to capture information. I was wondering what would be the best way to migrate these applications to managed code one app at a time. Any advice...
We work in native code, but porting the code base to managed world is my personal idea because I can see a lot of functionality that can be achieved in a better way if the code is written as managed code.
Thanks,
Byte
| You could write new parts of server using C++/CLI. It looks like a less painful option.
|
1,683,241 | 1,683,288 | Iterating over subsets of any size | I can iterate over the subsets of size 1
for( int a = 0; a < size; a++ ) {
or subsets of size 2
for( int a1 = 0; a1 < size; a1++ ) {
for( int a2 = a1+1; a2 < size; a2++ ) {
or 3
for( int a1 = 0; a1 < size; a1++ ) {
for( int a2 = a1+1; a2 < size; a2++ ) {
for( int a3 = a2+1; a3 < size; a3++ ) {
But how to do this for subsets of size n?
This does the job, based on an answer by Adam Rosenfield
void iterate(int *a, int i, int size, int n)
{
int start = 0;
if( i > 0 ) start = a[i-1]+1;
for(a[i] = start; a[i] < n; a[i]++) {
if(i == n-1) {
// a is the array of indices of size n
for( int k = 0; k < size; k++ ) {
printf("%d ",a[k]);
}
printf("\n");
}
else
iterate(a, i+1, size, n);
}
}
| You can use recursion:
void iterate(int *a, int i, int size, int n)
{
for(a[i] = 0; a[i] < size; a[i]++)
{
if(i == n-1)
DoStuff(a, n); // a is the array of indices of size n
else
iterate(a, i+1, size, n);
}
}
...
// Equivalent to 4 nested for loops
int a[4];
iterate(a, 0, size, 4);
|
1,683,263 | 1,683,401 | Convert std::vector<char*> to a c-style argument vector arv | I would like to prepare an old-school argument vector (argv) to use within the function
int execve(const char *filename, char
*const argv[],char *const envp[]);
I tried it with the stl::vector class:
std::string arguments = std::string("arg1");
std::vector<char*> argv;
char argument[128];
strcpy(argument, arguments.c_str());
argv.push_back(argument);
argv.push_back('\0'); // finish argv with zero
Finally I pass the vector to execve()
execve("bashscriptXY", &argv[0], NULL)
The code compiles but ArgV gets "ignored" by execve(). So it seems to be wrong, what I'm trying. How should I build an argV in a efficient way with c++?
| I think the char[128] is redundant as the string local will have the same lifetime, also, try adding the program as argv[0] like rossoft said in his answer:
const std::string arguments("arg1");
std::vector<const char*> argv;
argv.push_back("bashscriptXY");
// The string will live as long as a locally allocated char*
argv.push_back(arguments.c_str());
argv.push_back(NULL); // finish argv with zero
execve(argv[0], &argv[0], NULL);
|
1,683,367 | 1,683,377 | How to make two arrays into a function in c++? | I have two string arrays "Array1[size]" and "Array2[size]". They both have the same size.
I would like to write a function which contains this two arrays but I am having problems in the way that I am declaring them.
I am declaring it like this: void Thefunction (string& Array1[], string& Array2[], int size);
And when I call it I am calling it like this: Thefunction (Array1, Array2, size);
What I am doing wrong?
Thank you.
| You're declaring a function which takes arrays of string references. You almost certainly want to take arrays of strings.
Like this:
void TheFunction(string Array1[], string Array2[], int size);
|
1,683,540 | 1,684,836 | HttpSendRequest blocking when more than two downloads are already in progress | In our program, a new thread is created each time an HTTP request needs to be made, and there can be several running simultaneously. The problem I am having is that if I've got two threads already running, where they are looping on reading from InternetReadFile() after having called HttpSendRequest(), any subsequent attempts to call HttpSendRequest() just hang on that call, so I end up with the previously mentioned two threads continuing to read from their connections just fine, but the third just blocks on HttpSendRequest() until it times out.
From what I've been able to find on my own, this seems like it could just be the way wininet works, as the HTTP spec recommends: "A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy."
I've seen various programs handle multiple simultaneous downloads to the same server, but I'd imagine they need to do a lot of extra work to do that, in terms of managing the various connections, or writing their own http interface.
If it would require a lot of extra complexity to set it up to handle more than two active sessions, then I would just change things to only handle one or two files at a time, leaving the rest queued. However, if there were some low-complexity way to allow more than two at a time (off the top of my head, I'd guess using a new process per download might work, but would be messier), that would be preferable; it's not like it would be downloading more than 3-5 simultaneously anyway, and each download is at the user's request. I read some mentions of registry hacks to change the limit, but that's definitely not something I'd do. Any ideas?
| The HTTP 1.1 standard mandates a maximum of 2 simultaneous connections per server. If you have IE5, IE6, or IE7 installed, the versions of WinInet they install allow you to use InternetSetOption() to increase the limit (look at INTERNET_OPTION_MAX_CONNS_PER_SERVER and INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER options). However, the version of WinInet that is installed by with IE8 apparently disables that functionality (see http://connect.microsoft.com/WNDP/feedback/ViewFeedback.aspx?FeedbackID=434396 and http://connect.microsoft.com/WNDP/feedback/ViewFeedback.aspx?FeedbackID=481485).
|
1,683,665 | 1,684,009 | Where is Boost.Process? | I need to execute a program and retrieve its stdout output in c++. I'd like my code to be cross-platform too.
Having recently discovered the wonderful world of the Boost c++ libraries for all your cross platform needs, I figured I'd just go to boost.org and read up on the documentation of Boost.Process. Much to my surprise, it wasn't there! I then proceeded to figure out what name Boost gave their cross-platform library to start external processes, but haven't managed to find it so far.
A Google search brought me to Julio M. Merino Vidal's Boost.Process, which seems to be the unofficial Boost library I was looking for. Strangely enough, I cannot seem to find a download link on that website. It also seems like there haven't been any recent developments regarding the project.
I was finally able to find a download link for Vidal's Boost.Process on an external site and will use that for now, but I'm quite amazed at the effort I had to put in to get my hands on a cross platform c++ library to interact with external processes.
So, why is there no official Boost.Process? It seems like it would be a very valuable addition. Or am I totally overlooking the obvious solution here? Could you perhaps suggest other cross-platform libraries for managing simple starting of and interation with external processes?
| Julio M. Merino Vidal, who is, I beleive, the original author, wrote in this 2007 post that he did not have time to complete it.
Development was taken over by Boris Schaeling. This is the version that you found at http://www.highscore.de/boost/process/. According to this post, he is still actively developing it.
There is another version, by Ilya Sokolov.
For your other question:
Could you perhaps suggest other cross-platform libraries for managing simple starting of and interation with external processes?
you could look at this wiki page listing alternatives.
Depending on your needs, popen() could also do the job.
|
1,683,952 | 1,683,970 | C++ compilation error using string and istream_iterator | When trying to compile the following:
#include <string>
#include <iterator>
#include <iostream>
using namespace std;
int main() {
string s(istream_iterator<char>(cin), istream_iterator<char>());
return s.size();
}
g++ 4.4.1 gives me:
main.cc: In function ‘int main()’:
main.cc:6: error: request for member ‘size’ in ‘s’, which is of non-class type ‘std::string(std::istream_iterator<char, char, std::char_traits<char>, int>, std::istream_iterator<char, char, std::char_traits<char>, int> (*)())’
According to libstdc++ docs, string has a ctor that takes a begin/end iterator pair. Why do I get this error, then?
| You're accidentally declaring a function instead of instantiating a string. Try declaring variables for your istream_iterator objects and then passing those to the std::string constructor.
And here's a good read that describes exactly your problem: http://www.gotw.ca/gotw/075.htm
|
1,684,004 | 1,684,521 | Heap fragmentation and windows memory manager | I'm having trouble with memory fragmentation in my program and not being able to allocate very large memory blocks after a while. I've read the related posts on this forum - mainly this one. And I still have some questions.
I've been using a memory space profiler to get a picture of the memory. I wrote a 1 line program that contains cin >> var; and took a picture of the memory:
Where on the top arc - green indicates empty space, yellow allocated, red commited. My question is what is that allocated memory on the right? Is it the stack for the main thread? This memory isn't going to be freed and it splits the continuous memory that I need. In this simple 1 line program the split isn't as bad. My actual program has more stuff allocated right in the middle of the address space, and I don't know where it's comming from. I'm not allocating that memory yet.
How can I try solve this? I was thinking of switching to something like nedmalloc or dlmalloc. However that would only apply to the objects I allocate explicitly myself, whereas the split shown in the picture wouldn't go away? Or is there a way to replace the CRT allocation with another memory manager?
Speaking of objects, are there any wrappers for nedmalloc for c++ so I can use new and delete to allocate objects?
| First, thank you for using my tool. I hope you find it useful and feel free to submit feature requests or contributions.
Typically, thin slices at fixed points in the address space are caused by linked dlls loading at their preferred address. The ones that load high up in the address space tend to be Microsoft operating system dlls. It's more efficient for the operating system if these can all be loaded at their preferred addresses because then the read-only parts of the dlls can all be shared between processes.
The slice that you can see is nothing to worry about, it barely cuts anything out of your address space. As you've noted, there are dlls, though, which load at other points in the address space. IIRC shlwapi.dll is a particularly bad example, loading at about 0x2000000 (again IIRC) which often splits a large portion of the available address space into two smaller pieces. The problem with this is that once the DLL is loaded, there is nothing that you can do to move this allocate space around.
If you link against the DLL (either directly or via another DLL), there is nothing that you can do. If you use LoadLibrary you can get sneaky and reserve its preferred address, forcing it to be relocated - frequently somewhere better in the address space - before releasing that reserved memory. This doesn't always work, though.
Under the hood, Address Space Monitor uses VirtualQueryEx to examine the address space of the process but there is another call from the psapi library which other tools use (e.g. Process Explorer) which can show you which files (including DLLs) are mapped into which parts of the address space.
As you've found, it can be scarily easy to run out of room in a 2GB user address space. Fundamentally, you're best defence against memory fragmentation is simply to not require any large contiguous blocks of memory. Although difficult to retro-fit, designing your applicationg to work with 'medium sized' chunks usually makes substantially more efficient usage of the address space.
Similarly you can use a paging strategy, possibly using memory mapped files or Address Windowing Extensions.
|
1,684,418 | 1,684,439 | Why does the map size returns 0 | using namespace std;
class A {
public:
A() {}
~A() {}
map<int, string*>& getMap() {
return mapStr;
}
void setMap(const map<int,string*> m) {
mapStr = m;
}
private:
map <int, string*> mapStr;
};
class B {
public:
A getA() {
return a;
}
private:
A a;
};
int main(int argc, char*argv[]) {
map<int, string*> mm;
mm.insert(std::make_pair(1, new string("abc")));
mm.insert(std::make_pair(2, new string("def")));
B b;
b.getA().setMap(mm);
cout << "Size " << b.getA().getMap().size() << std::endl;
return 0;
}
Output:
Size 0
Any ideas as to why does this return the map size to be 0 and what needs to be done to be fixed
| Your getA method is returning a temporary copy of a, so your call to setMap is modifying that copy, not the original. One way to fix this would be to have getA return a reference or pointer to a
|
1,684,542 | 1,684,562 | C++ compiler - resolving name of a class member | When the compiler sees this code:
SomeClass foo;
int x = foo.bar;
What is the process it goes about in retrieving the value of bar? I.e. does it look at some data structure representing the class definition? If so is this data structure generated at compile time or runtime?
| The process starts when the compiler sees the definition for SomeClass. Based on that definition, it builds an internal structure that contains the types of the fields in SomeClass, and the locations of the code for the methods of SomeClass.
When you write SomeClass foo; the compiler finds the code that corresponds to the constructor for SomeClass, and creates machine instructions to call that code. On the next line you write int x = foo.bar. Here the compiler writes machine instructions to allocate stack space for an int, and then looks at its data structure for SomeClass. That data structure will tell it the offset in bytes of bar from the beginning of the foo object. The compiler then writes machine code to copy the bytes corresponding to bar into the memory for x. All of this machine code gets written into your executable.
Generally, the data structures representing SomeClass and other definitions are thrown away once compilation is done. What you have left is just a set of machine instructions. Those instructions are executed when you actually run your program, so that the constructor for SomeClass and the code to copy foo.bar into x are executed by the CPU without any explicit knowledge of the structure of your objects.
This is the general case. There are special cases for when you run your code under a debugger and for optimization, but this is generally what happens.
|
1,684,638 | 1,684,670 | a very simple c++ oop question | im struggling with syntax here: hopefully this question is v simple, im just miising the point.
specifically, if i nest a class within another class, so for instance
class a
{
a //the constructor
{
b an_instance_of_b // an instance of class b
}
};
class b
{
public:
foo()
{
cout << "foo";
}
};
When i try to access this method within B by doing this:
a an_instance_of_a; //declare an instance of a
an_instance_of_a.an_instance_of_b.foo()
^^ this doesnt seem to work. this is simplified (so might be a typo here somewhere). but i know the classes are being setup fine, its just that i cant access the methods inside them if they are nested. what may i be doing wrong?
many thanks.
| Your an_instance_of_b is not a member of a, but a local variable in the constructor of a (and the constructor declaration is missing the parenthesis).
What will happen here is that when you create an instance of a, it creates and immediately destroys an instance of b, then it leaves the constructor for a and the a instance is created.
|
1,684,815 | 1,684,845 | Expected constructor, destructor, or type conversion before '=' token | I have some extern'd variables in a namespace in a header file, and I'm trying to initialize them in its corresponding cpp file. However, I keep getting the error given in the topic title. I'm not sure what the problem is.
EX:
// Some header
namespace foo
{
extern SDL_Surface* bar;
}
// In the impl file
#include "someheader.h"
foo::bar = 0;
.....
Any assistance is appreciated. Thanks.
| At the file level, you can only define types (you've only written an assignment expression). So you need to change that to:
SDL_Surface* foo::bar = 0;
|
1,684,817 | 1,684,831 | c++: what exactly does &rand do? | This is an excerpt of some c++ code, that i'll have to explain in detail in some days:
std::vector<int> vct(8, 5);
std::generate(vct.begin(), vct.end(), &rand);
std::copy(vct.rbegin(), vct.rend(),
std::ostream_iterator<int>(std::cout, "\n"));
i think i understand everything about it, except that tiny mystical &rand. what exactly does it do? i mean obviously it produces some kind of pseudo-random-numbers, but they always remain the same. where does the &rand come from? what kind of expression is it? where do the values it produces come from? i'm a bit confused…
also, i could neither find any other occurrences of the word "rand" in the code, nor did i see any code that could have something to do with random numbers. that made me wonder, because my (very limited) experience in c++ showed, that only very few things simply work without having to be declared or included previously.
thanks for helping out!
| The & in &rand returns the address of the rand() function. You're passing a function pointer to generate() so generate() can call rand() to generate random numbers.
|
1,684,821 | 1,692,323 | is there a flag "M_FAST" in FreeBSD kernel for Malloc Call? | if you know there is one, can you let me know what its for ? if not please say so : ) thanks.
Signature : void * malloc(unsigned long size, struct malloc_type type, int flags);
for example. other flags are...
M_ZERO
Causes the allocated memory to be set to all zeros.
M_WAITOK
Indicates that it is OK to wait for resources. If the request
cannot be immediately fulfilled, the current process is put to
sleep to wait for resources to be released by other processes.
The malloc(), realloc(), and reallocf() functions cannot return
NULL if M_WAITOK is specified.**
This is the root of my confusion
EDIT:
The clarification for M_FAST is made in my answer below.
| M_FAST is not a flag, below. The answer was always there in the question I posted :P
It is a malloc_type type argument, which is used to perform statistics on the memory allocation.
For more information refer to the documentation from FreeBSD below,
(where, M_FOOBUF = M_FAST)
The type argument is used to perform statistics on memory usage, and for basic sanity checks. It can be used to identify multiple allocations. The statistics can be examined by `vmstat -m'.
A type is defined using struct malloc_type via the MALLOC_DECLARE() and MALLOC_DEFINE() macros.
/* sys/something/foo_extern.h */
MALLOC_DECLARE(M_FOOBUF);
/* sys/something/foo_main.c */
MALLOC_DEFINE(M_FOOBUF,"foobuffers","Buffers to foo data in to the ether");
/* sys/something/foo_subr.c */
buf = malloc(sizeof *buf, M_FOOBUF, M_NOWAIT);
In order to use MALLOC_DEFINE(), one must include (instead of ) and
|
1,684,941 | 1,686,584 | Need a little help with the Qt painting classes | I'm trying to write a paint program (paint where ever a mouse press/hold is detected), but I'm having trouble using the Qt QPainter. I have read the documentation on their web site and I'm still kind of lost. A link to a tutorial that isn't on their web site would be nice or maybe explain to me how I can accomplish this in Qt. The only thing I have managed to do is paint dots on a widget.
| Check the Scribble example that comes with Qt, it does exactly what you want.
We reimplement the mouse event
handlers to implement drawing, the
paint event handler to update the
application and the resize event
handler to optimize the application's
appearance. In addition we reimplement
the close event handler to intercept
the close events before terminating
the application.
The example also demonstrates how to
use QPainter to draw an image in real
time, as well as to repaint widgets.
|
1,684,975 | 1,685,124 | Strange segmentation fault C++ in _vfprintf_r() | Someone please see my code at this link for input taken from 2.2 mb file.
This produces seg fault. By gdb, it shows seg fault in _vfprintf_r(). But when I comment line 41 and uncomment 38 (a null statement), there is no segmentation fault. line no 41 is just print statement.
The output is written into result.txt file.
| You have a stack overflow. That's right, a Stack Overflow. I was able to reproduce by doing ulimit -s 1024. You need to not recurse so deeply, or you need to increase your stack size.
|
1,684,978 | 1,685,011 | Which one is preferred, return const double& OR return double | Given the following scenario, which one of the following is preferred.
m_state is a member rater than a local variable.
class C
{
private:
double m_state;
public:
double state() const { return m_state; } // returns double
double& state() { return m_state; }
}
===========================================
class C
{
private:
double m_state;
public:
const double& state() const { return m_state; } // returns const double&
double& state() { return m_state; }
}
| I wouldn't do this:
double& state() { return m_state; }
You may as well make m_state public if you did that. Probably what makes the most sense is:
const double & state() const { return m_state; }
Then again, when you're talking about saving the copy of a 64 bit variable (ie micro-optimization) and the fact that the latter version can be recast to whatever you want, I would just copy it:
double state() const { return m_state; }
(not that there's any true security anyway)
|
1,685,083 | 1,685,177 | Compiling Matlab to C++ Problem: fatal error C1083: Cannot open include file: 'windows.h' | I got this weird error when I was trying to compile matlab to C++ using the following command:
'mcc -W lib:cshared -d ' clibdir ' -T link:lib ' mfile
The error I got was:
fatal error C1083: Cannot open include
file: 'windows.h': No such file or
directory
Now, I was using lcc as my compiler ( instead of the Visual Studio one), and I made sure that Windows.h was inside the lcc\include directory (C:\Program Files\MATLAB\R2006a\sys\lcc\include), and yet, I still got the missing windows.h error even though I do have it inside the include folder.
Anyone has any idea why this is so?
Note: I have read similar questions at SO, and found that those problems are related to include folders not set etc. But I do have the include path set, I believe
| The error message you quote comes from Visual C++, so you're clearly not using lcc, and thus it won't make any difference what files you put in lcc's directories. Try running mbuild -setup to configure Matlab to use a different compiler command.
If you (or Matlab, on your behalf) are going to run the Visual C++ command-line compiler, then you should run it in a command prompt with all the right environment variables set up, such as the include path. Visual Studio should have put an item on your Start menu for that, or else you can run the vsvars32.bat file from within some other console window.
|
1,685,109 | 1,685,274 | Downloading HTTP URLs asynchronously in C++ | What's a good way to download HTTP URLs (e.g. such as http://0.0.0.0/foo.htm ) in C++ on Linux ? I strongly prefer something asynchronous. My program will have an event loop that repeatedly initiates multiple (very small) downloads and acts on them when they finish (either by polling or being notified somehow). I would rather not have to spawn multiple threads/processes to accomplish this. That shouldn't be necessary.
Should I look into libraries like libcurl? I suppose I could implement it manually with non-blocking TCP sockets and select() calls, but that would likely be less convenient.
| Libcurl is the way to go. See http://curlpp.org for C++ bindings and an excellent set of tutorials.
|
1,685,127 | 1,685,194 | Ability of SHFileOperation | Does SHFileOperation support to move and rename files at the same time?
I'v got a set of files :
c:\
f1.bmp f2.bmp f3.bmp f4.bmp
I want to move each to new folder, and rename them:
d:\
b1.bmp b2.bmp b3.bmp b4.bmp
Can I use SHFileOperation? and just do it once?
Many thanks!
| SHEFILEOPSTRUCT msdn
You can use the FOF_MULTIDESTFILES as stated in the msdn article: "The pTo member specifies multiple destination files (one for each source file in pFrom) rather than one directory where all source files are to be deposited." Perform a FO_MOVE operation with this flag.
|
1,685,339 | 1,685,399 | Verify Knuth shuffle algorithm is as unbiased as possible | I'm implementing a Knuth shuffle for a C++ project I'm working on. I'm trying to get the most unbiased results from my shuffle (and I'm not an expert on (pseudo)random number generation). I just want to make sure this is the most unbiased shuffle implementation.
draw_t is a byte type (typedef'd to unsigned char). items is the count of items in the list. I've included the code for random::get( draw_t max ) below.
for( draw_t pull_index = (items - 1); pull_index > 1; pull_index-- )
{
draw_t push_index = random::get( pull_index );
draw_t push_item = this->_list[push_index];
draw_t pull_item = this->_list[pull_index];
this->_list[push_index] = pull_item;
this->_list[pull_index] = push_item;
}
The random function I'm using has been modified to eliminate modulo bias. RAND_MAX is assigned to random::_internal_max.
draw_t random::get( draw_t max )
{
if( random::_is_seeded == false )
{
random::seed( );
}
int rand_value = random::_internal_max;
int max_rand_value = random::_internal_max - ( max - ( random::_internal_max % max ) );
do
{
rand_value = ::rand( );
} while( rand_value >= max_rand_value );
return static_cast< draw_t >( rand_value % max );
}
| Well, one thing you could do as a black-box test is take some relatively small array size, perform a large number of shuffles on it, count how many times you observe each permutation, and then perform Pearson's Chi-square test to determine whether the results are uniformly distributed over the permutation space.
On the other hand, the Knuth shuffle, AKA the Fisher-Yates shuffle, is proven to be unbiased as long as the random number generator that the indices are coming from is unbiased.
|
1,685,372 | 1,685,418 | Does the array key determine array size in C++? | im storing some settings for objects in an array. the id's of objects are used as the key. the id's start from 100000 and go up. if i was to input data for an object with id 100 000, would cpp automatical create 99999 blank key entries starting from 0?
| Array size is determined when you create an array.
To access object at index 100 000 you need to have array of at least that size, which answers your question.
If the array is smaller you will access memory at
array begin address + (index*object
size)
which is not a good thing. E.g. the following will print some data but it is a data that are stored at that point in memory and it's outside of your array (not a good thing):
string arr[3];
cout << arr[5] << endl;
Assuming you are talking about standard array like:
string arr[10];
Array's size is specified when you compile it, for example you can't do:
string arr[]; // this will fail to compile, no size specified
But you do:
string arr[] = {"1","2","3"}; // array size is 3
string arr1[3]; // array size is 3
string arr2[3] = {"1"}; // array size is 3
If you want to map extra parameters for object you are better off using std::map like:
class person {};
std::map<person*,int> PersonScore;
This assumes that the additional parameters are not logically part of the object otherwise you would just add them to the object.
|
1,685,549 | 1,685,562 | Returning pointer to structure to main function, getting segmentation error | #include<iostream>
using namespace std;
struct sample
{
int data[3][2];
};
struct sample* function()
{
struct sample s;
int c=1;
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
s.data[i][j]=c++;
cout<<"Matrix contents are ";
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
cout<<s.data[i][j])<<"\t";
cout<<"\n";
}
return &s;
}
int main()
{
struct sample *ss;
ss=function();
cout<<"Matrix contents are ";
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
cout<<ss->data[i][j]))<<"\t";
cout<<"\n";
}
return 0;
}
What is the error here? When I display content in that function it is getting output, but when I try to display contents outside of the function it displays garbage. What is wrong?
| Your s variable is allocated on the stack, and then you are returning a pointer to it; however, when the function ends, s no longer exists and the pointer is no longer valid.
You could either dynamically allocate s and return a reference/pointer to it, or you could return a copy of s rather than a reference.
In other words, you have a case of a dangling pointer.
|
1,685,556 | 1,685,596 | C++ vector to pointer of pointers | Is there a way to convert a vector to a pointer to a pointer (ptr-to-ptr).
Background:
I have an arbitrary length set of data stored in a vector. But I have a library of algorithms that accept ptr-to-ptr (for image array access). I need to get the data from my vector to a ptr-to-ptr. How is that possible?
| If you have a function void f(int **array) and a vector std::vector<int*> vect you can call f like this: f(&vect[0]). Is this what you were looking for?
|
1,685,808 | 1,685,903 | How to get the file/resource path for a QIcon | So let's say I do something like this:
QIcon myIcon(":/resources/icon.ico");
How can I later determine the path for that icon, e.g.
QString path = myIcon.getPath();
The problem is, there is no getPath() member, and I can't find anything similar, but surely there must be a way!
I guess I could inherit the QIcon class and add this functionality, but it's probably built in and I'm overlooking it?
| The filename isn't stored in QIcon, it's only used for constructing the image.
|
1,685,819 | 1,685,831 | How to convert _bstr_t to CString | I have a _bstr_t variable bstrErr and I am having a CString variable csError. How do I set the value which come in bstrErr to csError?
| Is it not possible just to cast it:
_bstr_t b("Steve");
CString cs;
cs = (LPCTSTR) b;
I think this should work when the project is Unicode.
|
1,685,836 | 1,695,159 | File backed Trie (or Prefix Tree) implementation | I have to store lot of strings in c++ map to keep unique strings and when ever duplicate string occurs I just need to increment the counter (pair.second). I've used c++ map and it well fits to this situation. Since the file that processing is gone now upto 30gig I am trying to keep this in a file instead of memory.
I also came across trie which is faster than map in this case. Any one aware of file backed trie implementation? I came across a Trie implementation similar to what I am looking for but not seems to be bug free ..
| If you can sort your file containing the strings, then reading the sorted list and counting duplicates would be easy. (You can retain the original file and create a new file of sorted strings.) Sorting large files efficiently is old technology. You should be able to find a utility for that.
If you can't sort, then consider digesting the strings. MD5 may be overkill for your purpose. You can cobble something up. For billions of strings, you could use 8 byte digests. Use a tree (probably a BST) of digests. For each digest, store the file offsets of the unique strings that produce that digest.
When you read a string, compute it's digest, and look it up. If you don't find the digest, you know the string is unique. Store it in the tree. If you do find the digest, check each associated string for a match and handle accordingly.
To compare strings, you will need to go to the file, since all you've stored is the file offsets.
What's important to remember it that if two digests are different, the strings that produced them must be different. If the digests are the same, the strings may not be the same, so you need to check. This algorithm will be more efficient when there are fewer duplicate strings.
|
1,685,858 | 1,685,879 | STL Sorting with Abstract Classes | I'm having a problem sorting my derived classes with the STL sort function.
Example -
The header:
vector<AbstractBaseClass *> *myVector;
In the ImpL:
sort(myVector->begin(), myVector->end(), compareBy);
The comparator:
bool MyClass::compareBy(AbstractBaseClass& a, AbstractBaseClass& b) {
return (a->someMethod() < b->someMethod());
}
Edit: This question is geared toward general usage of sorting abstract classes with the STL (I'm not posting a trace dump). If its not apparent already, I'll say that there is no way in hell it can compile as printed. Rather, I'm asking (given the data structures) how one would typically sort with this toy abstract class.
Thanks for the quick answers, I believe you guys already nail'd it!
Got'a love StackOverFlow!
| An example:
struct Abstr {
virtual int some()const == 0;
virtual ~Abstr() = default;
};
bool abstrSmaller( const Abstr* a1, const Abstr* a2 ) {
return a1->some() < a2->some();
}
int main() {
vector<Abstr*> v;
sort( v.begin(), v.end(), abstrSmaller );
}
The compare function should not be a member function: either a static or a free function.
It should take the vector's elements as argument, i.e. a pointer, not a reference.
It can call const functions, so it can accept const arguments.
|
1,686,002 | 1,686,039 | How to know the internet connection details using Visual C++ Win32 API | I have to create a log file for all internet connections made by PC. It should have details of the username, time of connection, etc. I do know about the InternetGetConnectedState() function which returns the boolean value. Know how do I get the other details. Can some one help me out thanks in advance. I am using Win32 API and Visual c++.
| You could use Network List Manager API to get list of networks using IEnumNetworks. Then use INetwork interface to get network information.
|
1,686,204 | 1,686,421 | Why should I not include cpp files and instead use a header? | So I finished my first C++ programming assignment and received my grade. But according to the grading, I lost marks for including cpp files instead of compiling and linking them. I'm not too clear on what that means.
Taking a look back at my code, I chose not to create header files for my classes, but did everything in the cpp files (it seemed to work fine without header files...). I'm guessing that the grader meant that I wrote '#include "mycppfile.cpp";' in some of my files.
My reasoning for #include'ing the cpp files was:
- Everything that was supposed to go into the header file was in my cpp file, so I pretended it was like a header file
- In monkey-see-monkey do fashion, I saw that other header files were #include'd in the files, so I did the same for my cpp file.
So what exactly did I do wrong, and why is it bad?
| To the best of my knowledge, the C++ standard knows no difference between header files and source files. As far as the language is concerned, any text file with legal code is the same as any other. However, although not illegal, including source files into your program will pretty much eliminate any advantages you would've got from separating your source files in the first place.
Essentially, what #include does is tell the preprocessor to take the entire file you've specified, and copy it into your active file before the compiler gets its hands on it. So when you include all the source files in your project together, there is fundamentally no difference between what you've done, and just making one huge source file without any separation at all.
"Oh, that's no big deal. If it runs, it's fine," I hear you cry. And in a sense, you'd be correct. But right now you're dealing with a tiny tiny little program, and a nice and relatively unencumbered CPU to compile it for you. You won't always be so lucky.
If you ever delve into the realms of serious computer programming, you'll be seeing projects with line counts that can reach millions, rather than dozens. That's a lot of lines. And if you try to compile one of these on a modern desktop computer, it can take a matter of hours instead of seconds.
"Oh no! That sounds horrible! However can I prevent this dire fate?!" Unfortunately, there's not much you can do about that. If it takes hours to compile, it takes hours to compile. But that only really matters the first time -- once you've compiled it once, there's no reason to compile it again.
Unless you change something.
Now, if you had two million lines of code merged together into one giant behemoth, and need to do a simple bug fix such as, say, x = y + 1, that means you have to compile all two million lines again in order to test this. And if you find out that you meant to do a x = y - 1 instead, then again, two million lines of compile are waiting for you. That's many hours of time wasted that could be better spent doing anything else.
"But I hate being unproductive! If only there was some way to compile distinct parts of my codebase individually, and somehow link them together afterwards!" An excellent idea, in theory. But what if your program needs to know what's going on in a different file? It's impossible to completely separate your codebase unless you want to run a bunch of tiny tiny .exe files instead.
"But surely it must be possible! Programming sounds like pure torture otherwise! What if I found some way to separate interface from implementation? Say by taking just enough information from these distinct code segments to identify them to the rest of the program, and putting them in some sort of header file instead? And that way, I can use the #include preprocessor directive to bring in only the information necessary to compile!"
Hmm. You might be on to something there. Let me know how that works out for you.
|
1,686,332 | 1,686,384 | How do I use _W64 and __w64 in VC++? | There's such thing as __w64 in Visual C++ 9. I came across it while trying to port my native C++ DLL to 64 bit. In particular in crtdefs.h there's this nice snippet:
#if !defined(_W64)
#if !defined(__midl) && (defined(_X86_) || defined (_M_IX86)) && _MSC_VER >= 1300
#define _W64 __w64
#else
#define _W64
#endif
#endif
which if I get it right implies that for 64 bit _W64 is defined as an empty string and has no effect, but for 32 bit it is defined as __w64.
I tried defining _W64 to be an empty string and __w64 in turn and at least both time the project compiles fine in 64-bit configuration.
That said both _W64 and __w64 look useless. How am I intended to use them and how should I define _W64 in 64-bit projects?
| The answer is, you don't. It's a compiler feature for use by the 32 bits compiler. The original idea was that Microsoft wanted to prepare programmers for the upcoming 32->64 bits transition. Therefore, the 32 bits compiler gained the ability to label certain typedefs as __w64. Microsoft then used that ability to label typedefs that would change in Win64.
|
1,686,348 | 1,687,113 | What is #defined if a compiler is Cpp0x compliant? | Is there any official, or inofficial, #defines for when a compiler is Cpp0x compliant?
Even better, for specific Cpp0x functionality (~#cpp0xlambda, #cpp0xrvalue etc)?
(Haven't found anything about this on the net)
| Bjarne's C++0x FAQ says:
__cplusplus
In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.
|
1,686,385 | 1,687,020 | Overloading operator>> to a char buffer in C++ - can I tell the stream length? | I'm on a custom C++ crash course. I've known the basics for many years, but I'm currently trying to refresh my memory and learn more. To that end, as my second task (after writing a stack class based on linked lists), I'm writing my own string class.
It's gone pretty smoothly until now; I want to overload operator>> that I can do stuff like cin >> my_string;.
The problem is that I don't know how to read the istream properly (or perhaps the problem is that I don't know streams...). I tried a while (!stream.eof()) loop that .read()s 128 bytes at a time, but as one might expect, it stops only on EOF. I want it to read to a newline, like you get with cin >> to a std::string.
My string class has an alloc(size_t new_size) function that (re)allocates memory, and an append(const char *) function that does that part, but I obviously need to know the amount of memory to allocate before I can write to the buffer.
Any advice on how to implement this? I tried getting the istream length with seekg() and tellg(), to no avail (it returns -1), and as I said looping until EOF (doesn't stop reading at a newline) reading one chunk at a time.
| To read characters from the stream until the end of line use a loop.
char c;
while(istr.get(c) && c != '\n')
{
// Apped 'c' to the end of your string.
}
// If you want to put the '\n' back onto the stream
// use istr.unget(c) here
// But I think its safe to say that dropping the '\n' is fine.
If you run out of room reallocate your buffer with a bigger size.
Copy the data across and continue. No need to be fancy for a learning project.
|
1,686,390 | 1,686,400 | Python-equivalent of short-form "if" in C++ |
Possible Duplicate:
Python Ternary Operator
Is there a way to write this C/C++ code in Python?
a = (b == true ? "123" : "456" )
| a = '123' if b else '456'
|
1,686,423 | 1,686,957 | Downside of this macro construct and possible alternatives | I recently saw some code using macros like
#define CONTAINS(Class, Name)\
private:\
std::list<Class> m_##Name##s;\
public:\
void add_##Name(const Class& a_##Name) {\
m_##Name##s.push_back(a_##Name);\
}\
int get_##Name(int pos) {\
return m_##Name##s.at(pos);\
}\
// ... more member functions
Later you can declare a class like
class my_class {
CONTAINS(int, integer)
// ...
};
and write
my_class a(...);
a.add_integer(10);
I was puzzled about this paste-in-macro-style because I'm missing concrete counter-arguments. But beside that I accept the following pros
you can easily add a list interface for arbitrary types to your class
you avoid frequently repeated code
you have an easy to use interface (like add_integer(10))
Now I'm searching for alternatives which meet all these points above and avoid this old C macro style. My first idea was to create an abstract base class template
template<typename T>
class list_interface {
private:
std::list<T> m_list;
public:
void add_element(const T& x) {
m_list.push_back(x);
}
// ... more member functions
};
and add it to my class via inheritance like this
class my_class : public list_interface<int> {
// ...
};
Now I can write too
my_class a;
a.add_element(10);
but I'm concerned about the following points:
you can only add one list to your class
you publicly inherit from a class without virtual destructor
I don't meet the third point of the pros (add_element(10) instead of add_integer(10))
My questions are:
What are the drawbacks of the old C macro construct
How can I provide a similar functionality without macros
| How about:
#include <vector>
template<typename T>
class Plop
{
std::vector<T> data;
public:
void add(T const& v) {data.push_back(v);}
T get(int pos) {return data.at(pos);} // at() is not valid on lists.
};
class my_class
{
public:
Plop<int> integer;
Plop<float> floater;
};
int main()
{
my_class x;
x.integer.add(5); // similar to x.add_integer(5);
x.integer.get(0); // similar to x.get_integer(0);
}
It meets all the requirements:
you can easily add a list interface for arbitrary types to your class
you avoid frequently repeated code
you have an easy to use interface (like add_integer(10))
My questions are:
What are the drawbacks of the old C macro construct
The ick factor.
Debugging.
Can pass individual list to other functions or methods.
How can I provide a similar functionality without macros
See above.
|
1,687,085 | 1,687,121 | C++ map really slow? | i've created a dll for gamemaker. dll's arrays where really slow so after asking around a bit i learnt i could use maps in c++ and make a dll.
anyway, ill represent what i need to store in a 3d array:
information[id][number][number]
the id corresponds to an objects id. the first number field ranges from 0 - 3 and each number represents a different setting. the 2nd number field represents the value for the setting in number field 1.
so..
information[101][1][4];
information[101][2][4];
information[101][3][4];
this would translate to "object with id 101 has a value of 4 for settings 1, 2 and 3".
i did this to try and copy it with maps:
//declared as a class member
map<double, map<int, double>*> objIdMap;
///// lower down the page, in some function
map<int, double> objSettingsMap;
objSettingsMap[1] = 4;
objSettingsMap[2] = 4;
objSettingsMap[3] = 4;
map<int, double>* temp = &objSettingsMap;
objIdMap[id] = temp;
so the first map, objIdMap stores the id as the key, and a pointer to another map which stores the number representing the setting as the key, and the value of the setting as the value.
however, this is for a game, so new objects with their own id's and settings might need to be stored (sometimes a hundred or so new ones every few seconds), and the existing ones constantly need to retrieve the values for every step of the game. are maps not able to handle this? i has a very similar thing going with game maker's array's and it worked fine.
| 1) Your code is buggy: You store a pointer to a local object objSettingsMap which will be destroyed as soon as it goes out of scope. You must store a map obj, not a pointer to it, so the local map will be copied into this object.
2) Maps can become arbitrarily large (i have maps with millions of entrys). If you need speed try hash_maps (part of C++0x, but also available from other sources), which are considerably faster. But adding some hundred entries each second shouldn't be a problem. But befre worring about execution speed you should always use a profiler.
3) I am not really sure if your nested structures MUST be maps. Depending of what number of setting you have, and what values they may have, a structure or bitfield or a vector might be more accurate.
|
1,687,152 | 1,687,186 | stl vector and c++: how to .resize without a default constructor? | How do I tell STL, specifically for the method resize() in vector, to initialize objects with a constructor other than default, and with which parameters?
For example:
class something {
int a;
something (int value);
}
std::vector<something> many_things;
many_things.resize (20);
More generally, how do I force STL to use my constructor when it needs to create objects, and pass parameters to that constructor?
In my case adding a default constructor is not an option, and I'd prefer not to use an array of pointers to solve the problem.
| Use the 2-argument overload:
many_things.resize(20, something(5));
|
1,687,358 | 1,687,370 | C++ positional parameters | This is a very basic question, so please bear with me.
Consider the following function in C++:
void foo(int a, int b, int c)
{
//do something
}
can I call this function like this: foo(b=2, c=3, a=2) ?
I suppose this have some sort of name (positional parameters, possibly). If you could clarify it in the answer too, it would great.
| Not in standard C++, no. You'll have to provide the parameters in the order specified by the function prototype.
|
1,687,437 | 1,687,461 | How to call C++ functions/methods via JavaScript | does anybody know how to call C++ functions or methods via JavaScript.
Need scripting like Lua/Python-C++ but with JavaScript.
Thanks in advance.
| You can try Google's V8:
open source JavaScript engine.
V8 is written in C++ and is used in Google Chrome, the open source browser from Google.
V8 implements ECMAScript as specified in ECMA-262, 3rd edition, and runs on Windows XP and Vista, Mac OS X 10.5 (Leopard), and Linux systems that use IA-32 or ARM processors.
V8 can run standalone, or can be embedded into any C++ application...
|
1,687,558 | 1,687,611 | Calling unmanaged function from C#: should I pass StringBuilder or use unsafe code? | I've got a C# program that needs to pass a char buffer to an unmanaged function. I've found two ways that seem to work reliably, but I'm not sure which I should choose.
Here's the unmanaged function's signature.
extern "C" __declspec(dllexport) int getNextResponse(char *buffer);
The first option is to define the buffer as a StringBuilder, as follows.
//at class level...
[DllImport("mydll.dll")]
static extern int getNextResponse(StringBuilder buffer);
//in main method body...
StringBuilder sb = new StringBuilder(" ", 65536);
int rc = getNextResponse(sb);
This is simple, and it works, and I think I basically understand why it works because the StringBuilder has a buffer behind the scenes, so (I assume) the interop layer is just marshalling the StringBuilder to a char *.
The other option is using unsafe code.
//at class level...
[DllImport("mydll.dll")]
static extern int getNextResponse(byte* buffer);
//separate method...
private static unsafe int runGetNextResponse(byte[] buffer)
{
fixed (byte* p = buffer)
{
int rc = getNextResponse(p);
return rc;
}
}
//in main method body...
byte[] b = new byte[65536];
int rc = runGetNextResponse(b);
The second approach is more code, but it's also more explicit about what's going on.
Are these two approaches doing basically the same thing? Is there any reason to choose one over the other?
| I'd strongly prefer using the StringBuilder version.
There's not going to be a huge difference between the two, and using unsafe code is not nearly as clean.
In my opinion, since there is a way to solve the problem using a core library class, using unsafe code without a clear (and needed) benefit is a premature optimization.
|
1,687,579 | 1,687,617 | boost serialization access to protected data | When I try to serialize class with protected members, I get the following errors:
"cannot access protected member declared in class NetElement". The idea is that I'd like to have one serialization function outside of class definition. What am I doing wrong?
best regards,
mightydodol
Here is the code...
// class definition
class NetElement
{
friend class boost::serialization::access;
protected:
int nelements;
int ids;
public:
static NetElement* New(){return new NetElement;}
virtual void Delete(){delete this;}
protected:
NetElement(){};
~NetElement(){};
};
// nonintrusive serialize
template<class Archive>
void serialize(Archive & ar, NetElement& element, const unsigned int version=1)
{
ar & element.nelements & element.ids;
}
int main(void)
{...
std::ofstream os("Pipe1.txt");
boost::archive::text_oarchive oa(os);
serialize(oa,el/*ref to NetElementObj*/);
...
}
| Like any other non-member function, your serialize function can only access the public members of NetElement. If, as is often the case, the public interface doesn't expose enough state to serialize the object, then you'll need to make the serialize function a member.
In this case, though, the state is protected, so you could get to it using an "accessor" class derived from NetElement:
class NetElementAccessor : private NetElement
{
public:
explicit NetElementAccessor(const NetElement &e) : NetElement(e) {}
using NetElement::nelements;
using NetElement::ids;
};
template<class Archive>
void serialize(Archive & ar, NetElement& element, const unsigned int version=1)
{
NetElementAccessor accessor(element);
ar & accessor.nelements & accessor.ids;
}
The downside is that this copies the object before serialising it.
|
1,687,860 | 1,688,142 | Why is type_info declared outside namespace std? | I'm using VS2005 and the MS implementation of STL. However, the class type_info in is declared outside of "namespace std". This creates some problems for third party libs that excepts to find a std::type_info. Why is this so, and is there any workaround? Here is a sample from the beginning of typeinfo:
class type_info {
...
};
_STD_BEGIN // = namespace std {
| That's interesting - the standard does say that (17.4.1.1. Library contents)
All library entities except macros, operator new and operator delete are defined within the namespace std or namespaces nested within namespace std.
And clearly says that (5.2.8 Type identification)
The result of a typeid expression is an lvalue of static type const std::type_info (18.5.1) and dynamic type const std::type_info or const name where name is an implementation-defined class derived from std::type_info which preserves the behavior described in 18.5.1.
Ans, of course, the descriptin of header <typeinfo?> indicate the it should be in namespace std (18.5 Type identification):
Header <typeinfo> synopsis
namespace std {
class type_info;
class bad_cast;
class bad_typeid;
}
So type_info should be in the std namespace (and not outside of it). I guess that either this is a bug or there's some large set of code (or small set of important code) that needs it outside of the std namespace. I'd have thought they'd use some preprocessor magic to make it so you could force it to be in the std namespace if desired (or the other way around - make it in std by default and allow a macro or something to force it to the global namespace).
However, one additional wrinkle for type_info is that it's the result of the typeid operator (more precisely, something derived from type_info is the result), so there's probably a tight dependency on what the compiler does for the typeid operator that the library needs to be in line with. So the fact that type_info isn't in namespace std is possibly due to what the compiler does with typeid expressions, and the library writers probably have little direct control over that (and I'd guess that's one reason why there's no preprocssor workaround for the problem). Someone who knows a lot more about how compilers work than I do would have to explain this better (or take it beyond speculation).
But I think you'll have to ask someone at Microsoft (or PJ Plauger/Dinkumware) for a real answer to "why".
|
1,687,888 | 1,687,993 | Is there a good way of setting C/C++ member variables from string representations? (introspection-lite) | I've got a struct with some members that I want to be able to get and set from a string. Given that C++ doesn't have any introspection I figure I need some creative solution with macros, the stringize operator and maybe boost::bind. I don't need full serialization or introspection, more an 'introspection-lite'
I'd like to have something along the lines of this:
struct MyType {
int fieldA;
int fieldB;
};
DECLARE_STRING_MAP(MyType,fieldA);
DECLARE_STRING_MAP(MyType,fieldB);
MyType t;
SET_VALUE_FROM_STRING(MyType,t,"fieldA","3")
Rather than have a huge if statement.
Any idea if there's a neat solution to this?
Related question: Object Reflection
EDIT:
Thanks to maxim1000 for the 'map to int Type::*' trick -- this worked for me:
#define DEFINE_LOOKUP_MAP(Type) std::map<AnsiString,int Type::*> mapper
#define ADD_FIELD_MAPPING(Type, Field) mapper[#Field]=&Type::Field
#define SET_FIELD_FROM_MAP(Type, Field, var, value) var.*(mapper[#Field])=value
DEFINE_LOOKUP_MAP(MyType);
ADD_FIELD_MAPPING(MyType, fieldA);
ADD_FIELD_MAPPING(MyType, fieldB);
SET_FIELD_FROM_MAP(MyType, fieldA, obj, 3);
| If all of them have the same type, you can use something like this:
std::map<std::string,int MyType::*> mapper;
mapper["fieldA"]=&MyType::fieldA;
mapper["fieldB"]=&MyType::fieldB;
...
MyType obj;
obj.*(mapper["fieldA"])=3;
|
1,689,019 | 1,689,069 | Watch a memory location/install 'data breakpoint' from code? | We have a memory overwrite problem. At some point, during the course of our program, a memory location is being overwritten and causing our program to crash. the problem happens only in release mode. when in debug, all is well.
that is a classic C/C++ bug, and a very hard one to locate.
I wondered if there's a way to add some 'debugging code' that will watch this memory location and will call a callback once its changed. This is basically what a debugger could do in debug mode (a 'data breakpoint') but we need something similar in release.
| If you can control the location of the variable then you can allocate it on a dedicated page and set the permissions of the page to allow reads only using VirtualProtect (on Windows ... not sure for Linux).
This way you will get an access violation when someone tries to write to it. With an exception translator function you could treat this as a callback.
Even if you can't move the variable directly (eg. it is a class member), maybe you could add sufficient padding around the variable to ensure it is on a dedicated page and use the same approach.
|
1,689,148 | 1,689,469 | Error in Visual Studio | I get this error in visual studio and I don't know the reason. It doesn't even show the line number. Any clue?
Error 1 error LNK2028: unresolved
token (0A000041) "void __cdecl
free_img(struct Image *)"
(?free_img@@$$FYAXPAUImage@@@Z)
referenced in function "double *
__cdecl calc_zernike_moments(struct Image const *,int,struct ZernikeBasis
const *)"
(?calc_zernike_moments@@$$FYAPANPBUImage@@HPBUZernikeBasis@@@Z) zernike_moments.obj TestLibrary
| free_img() is a function that is either defined in a .cpp file that you haven't included in the project, or it is in a DLL or static library that you haven't linked against. If it is the former, you need to search for the function in your source files and then add that .cpp file to the project. If it is the latter, then you need to identify which library provides free_img() and then locate the .lib file for that library. Then you can do this:
To add .lib files as linker input in the development environment
Open the project's Property Pages dialog box. For details, see Setting Visual C++ Project Properties.
Click the Linker folder.
Click the Input property page.
Modify the Additional Dependencies property.
(from http://msdn.microsoft.com/en-us/library/ba1z7822(VS.80).aspx)
|
1,689,195 | 1,689,267 | What the C++ rules in regard to covariant return types? | Like in the example below, what is allowed, how and why?
class Shape {
public:
//...
virtual Shape *clone() const = 0; // Prototype
//...
};
class Circle : public Shape {
public:
Circle *clone() const;
//...
};
| C++ Standard 2003. 10.3.5
The return type of an overriding
function shall be either identical to
the return type of the overridden
function or covariant with the classes
of the functions. If a function D::f
overrides a function B::f, the return
types of the functions are covariant
if they satisfy the following
criteria:
— both are pointers to classes or
references to classes
— the class in the return type of
B::f is the same class as the class in
the return type of D::f, or is an
unambiguous and accessible direct or
indirect base class of the class in
the return type of D::f
— both pointers or references have
the same cv-qualification and the
class type in the return type of D::f
has the same cv-qualification as or
less cv-qualification than the class
type in the return type of B::f.
If the return type of D::f differs
from the return type of B::f, the
class type in the return type of D::f
shall be complete at the point of
declaration of D::f or shall be the
class type D. When the overriding
function is called as the final
overrider of the overridden function,
its result is converted to the type
returned by the (statically chosen)
overridden function (5.2.2).
Example:
class B {};
class D : private B { friend class Derived; };
struct Base {
virtual B* vf4();
virtual B* vf5();
};
class A;
struct Derived : public Base {
D* vf4(); // OK: returns pointer to derived class
A* vf5(); // error: returns pointer to incomplete class
};
|
1,689,896 | 1,704,255 | Qt Dialog Window Opens in Same Window | I managed to get a QPushButton to open a new window when pressed by using the following code (just snippets of code):
AppDialog::AppDialog(QWidget *parent)
: QDialog(parent)
{
QPushButton *button3 = new QPushButton(tr("Apps"));
QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->addWidget(button3);
setLayout(hLayout);
}
MainWindow::MainWindow()
{
mainMenu = new MainMenu;
setCentralWidget(mainMenu);
app = 0;
readSettings();
}
void MainWindow::AppMenu()
{
app = new AppDialog(this);
app->show();
}
This opens in a new window with an "App" button in it. Can anyone let me know if it's possible and how to open the new app dialog in the same window as the original main menu? It should cover the whole window and look like a normal window with the new menu on it. Ideally after this I could add a "back" button of some sort. I guess this is similar to creating a "wizard" type of interface that is used a lot on the installation wizards and stuff like that.
Bryce
EDIT
This is the source code for implementing QStackedWidgets()
MainMenu::MainMenu(QWidget *parent)
: QDialog(parent)
{
QStackedLayout *stackedLayout = new QStackedLayout;
AppDialog *app = new AppDialog;
progWidget *program = new ProgWidget;
QStackedWidget *stackedWidget = new QStackedWidget;
stackedWidget->addWidget(app);
stackedWidget->addWidget(program);
stackedWidget->setCurrentIndex(0);
QVBoxLayout *vLayout = new QVBoxLayout;
vLayout->addWidget(stackedWidget);
setLayout(vLayout);
}
Where would I put the signals and slots to change the index? Imaging that the app and program widgets are just a few widgets with some QPushButtons on them. I can get them to display separately but haven't figure out how to change them yet.
| You might want to look at this question. My answer here is the same... use a QStackedWidget as your main widget, and the stuff you want to be different on each page inside it. (If that is the whole dialog, then make the stacked widget cover the whole dialog). Then you can set the current page of the stacked widget based on whatever logic you want to use, such as clicking a button, and it will hide everything from the previous page and show the new current page.
==EDIT==
To clarify based on your example, you could do something like this:
enum Pages { FIRST, SECOND, LAST };
MainMenu::MainMenu(QWidget *parent)
: QDialog(parent)
{
// Create widgets to populate the pages
QWidget* widgets[3];
widgets[FIRST] = new QWidget;
widgets[SECOND] = new QWidget;
widgets[LAST] = new QWidget;
// Create buttons to navigate between the pages
QPushButton* buttons[3];
buttons[FIRST] = new QPushButton(widgets[FIRST]);
buttons[FIRST]->setText("Next");
buttons[FIRST]->setSize(100, 100);
buttons[FIRST]->show();
buttons[SECOND] = new QPushButton(widgets[SECOND]);
buttons[SECOND]->setText("Next");
buttons[SECOND]->setSize(100, 100);
buttons[SECOND]->show();
buttons[LAST] = new QPushButton(widgets[LAST]);
buttons[LAST]->setText("Start Again");
buttons[LAST]->setSize(100, 100);
buttons[LAST]->show();
// Create stacked widget for the pages
QStackedWidget *stackedWidget = new QStackedWidget;
stackedWidget->addWidget(widgets[FIRST]);
stackedWidget->addWidget(widgets[SECOND]);
stackedWidget->addWidget(widgets[LAST]);
stackedWidget->setCurrentIndex(0);
QVBoxLayout *vLayout = new QVBoxLayout;
vLayout->addWidget(stackedWidget);
setLayout(vLayout);
// Changes a bunch of signals into one signal with an index.
QSignalMapper *mapper(this);
for(int i = 0; i < 3; ++i)
{
// Each button maps to the next id, with the last one wrapping around.
mapper->setMapping(buttons[i], (i + 1) % 3);
// Make the button click connect to the mapper.
connect(buttons[i], SIGNAL(clicked()), mapper, SLOT(map()));
}
// Connect the collected (and slightly transformed) signal to change the page.
connect(mapper, SIGNAL(mapped(int)), stackedWidget, SLOT(setCurrentIndex(int)));
}
|
1,690,082 | 1,690,112 | Combining wide string literal with string macro | I have a macro for a character string as follows:
#define APPNAME "MyApp"
Now I want to construct a wide string using this macro by doing something like:
const wchar_t *AppProgID = APPNAME L".Document";
However, this generates a "concatenating mismatched strings" compilation error.
Is there a way to convert the APPNAME macro to a wide string literal?
| Did you try
#define APPNAME "MyApp"
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
const wchar_t *AppProgID = WIDEN(APPNAME) L".Document";
|
1,690,212 | 1,690,288 | Cross-platform C++ application with .NET GUI? | I have a few years of experience in cross-platform desktop development (Windows and MacOSX, not Linux (at least not for GUI apps)). Usually I create the GUI on MacOSX with Cocoa, and on Windows I use the old-fashioned Windows API. I have not used Qt because when I started it was still under the GPL license.
I find the native experience very important so I'll keep using Cocoa for Mac. However for Windows I am considering using the .NET framework for the GUI code. I have no experience integrating .NET code with an existing cross-platform C++ code base and it seems that I can go with C++/CLI or C#.
Has anyone done such an approach before? Did it work out well? Do you need to bundle the .NET framework with the installer? Does the added .NET code add a lot of weight to the final executable?
| Yes, you need to bundle the .NET framework with the installer or notify the user that they need to install it and provide a link if it's not already installed. In my experience, the added .NET code does add some appreciable weight to the executable, but I've found it to be more inconvenient having to install the .NET framework on machines that did not have it - the installation does take some considerable amount of time.
|
1,690,261 | 1,797,938 | Why do I get a CL_MEM_OBJECT_ALLOCATION_FAILURE? | I'm allocating a cl_mem buffer on a GPU and work on it, which works fine until a certain size is exceeded. In that case the allocation itself succeeds, but execution or copying does not. I do want to use the device's memory for faster operation so I allocate like:
buf = clCreateBuffer (cxGPUContext, CL_MEM_WRITE_ONLY, buf_size, NULL, &ciErrNum);
Now what I don't understand is the size limit. I'm copying about 16 Mbyte but should be able to use about 128 Mbyte (see CL_DEVICE_MAX_MEM_ALLOC_SIZE ).
Why do these numbers differ so much ?
Here's some excerpt from oclDeviceQuery:
CL_PLATFORM_NAME: NVIDIA
CL_PLATFORM_VERSION: OpenCL 1.0
OpenCL SDK Version: 4788711
CL_DEVICE_NAME: GeForce 8600 GTS
CL_DEVICE_TYPE: CL_DEVICE_TYPE_GPU
CL_DEVICE_ADDRESS_BITS: 32
CL_DEVICE_MAX_MEM_ALLOC_SIZE: 128 MByte
CL_DEVICE_GLOBAL_MEM_SIZE: 255 MByte
CL_DEVICE_LOCAL_MEM_TYPE: local
CL_DEVICE_LOCAL_MEM_SIZE: 16 KByte
CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE: 64 KByte
| clCreateBuffer will not actually create a buffer on the device. This makes sense, since at the time of creation the driver does not know which device will use the buffer (recall that a context can have multiple devices). The buffer will be created on the actual device when you enqueue a write or when you launch a kernel that takes the buffer as a parameter.
As for the 16MB limit, are you using the latest driver (195.xx)? If so you should contact NVIDIA either through the forums or directly.
|
1,690,675 | 1,690,694 | Implementing a default constructor | I am trying to implement a DateTime class in C++:
class DateTime {
public:
DateTime();
DateTime(time_t ticks);
DateTime(int day, int month, int year);
DateTime(int day, int month, int year, int hour, int minute, int second);
//...
private:
time_t ticks;
int day;
int month;
//...
}
then in application:
DateTime date1; //default constructor
I know that having a default constructor is required for c++, but how should I implement it in this situation?
Should it set all properties to 0? That would make all other methods work, but doesn't really seem intuitive...
Should it just leave all properties un-initialized? That would make none of its methods work, but it seems more intuitive than 0, because you haven't done anything to it yet.
Should it set an internal bool initialized=false then all methods check that before operating on it?
I'm not really sure on this one. Is there a "standard" way of doing it?
| Typically, the default constructor would initialize you to a "default" reference time.
If you're using a time_t internally, setting it to time_t of 0 (Unix epoch, which is 1/1/1970) would be a reasonable option, since "0" values are common defaults.
That being said, a default constructor is not required in C++ - you can have a type with no default constructor, which would require a valid "time" to be specified.
|
1,691,007 | 1,691,310 | What's the right way to overload operator== for a class hierarchy? | Suppose I have the following class hierarchy:
class A
{
int foo;
virtual ~A() = 0;
};
A::~A() {}
class B : public A
{
int bar;
};
class C : public A
{
int baz;
};
What's the right way to overload operator== for these classes? If I make them all free functions, then B and C can't leverage A's version without casting. It would also prevent someone from doing a deep comparison having only references to A. If I make them virtual member functions, then a derived version might look like this:
bool B::operator==(const A& rhs) const
{
const B* ptr = dynamic_cast<const B*>(&rhs);
if (ptr != 0) {
return (bar == ptr->bar) && (A::operator==(*this, rhs));
}
else {
return false;
}
}
Again, I still have to cast (and it feels wrong). Is there a preferred way to do this?
Update:
There are only two answers so far, but it looks like the right way is analogous to the assignment operator:
Make non-leaf classes abstract
Protected non-virtual in the non-leaf classes
Public non-virtual in the leaf classes
Any user attempt to compare two objects of different types will not compile because the base function is protected, and the leaf classes can leverage the parent's version to compare that part of the data.
| For this sort of hierarchy I would definitely follow the Scott Meyer's Effective C++ advice and avoid having any concrete base classes. You appear to be doing this in any case.
I would implement operator== as a free functions, probably friends, only for the concrete leaf-node class types.
If the base class has to have data members, then I would provide a (probably protected) non-virtual helper function in the base class (isEqual, say) which the derived classes' operator== could use.
E.g.
bool operator==(const B& lhs, const B& rhs)
{
return lhs.isEqual( rhs ) && lhs.bar == rhs.bar;
}
By avoiding having an operator== that works on abstract base classes and keeping compare functions protected, you don't ever get accidentally fallbacks in client code where only the base part of two differently typed objects are compared.
I'm not sure whether I'd implement a virtual compare function with a dynamic_cast, I would be reluctant to do this but if there was a proven need for it I would probably go with a pure virtual function in the base class (not operator==) which was then overriden in the concrete derived classes as something like this, using the operator== for the derived class.
bool B::pubIsEqual( const A& rhs ) const
{
const B* b = dynamic_cast< const B* >( &rhs );
return b != NULL && *this == *b;
}
|
1,691,100 | 1,691,135 | Is there anything wrong with the way that this C++ header is laid out? | #pragma once
#include "LudoCore/Singleton.h"
class LudoTimer : public Singleton<LudoTimer>
{
friend class Singleton<LudoTimer>;
public:
void Update();
void ShortenDay();
void LengthenDay();
UINT64 GetDeltaTime() const;
float GetPercentageOfDayElapsed() const;
private:
LudoTimer();
~LudoTimer();
UINT64 GetTickCount64() const;
UINT64 GetElapsedSeconds() const;
UINT64 m_DeltaTime;
// Tick Count
UINT64 m_CurrFrameTick;
UINT64 m_LastFrameTick;
int m_SecondsInADay;
static const int SHORTEST_POSSIBLE_DAY = 60;
static const int LONGEST_POSSIBLE_DAY = 86400;
static const int CHANGING_INTERVAL = 600;
};
To me, the above code looks normal. However, I'm new to C++ so I may be missing some nuance. I'm getting a bunch of compiler errors from it, such as:
error C2447: '{' : missing function header (old-style formal list?)
and
error C2236: unexpected 'class'
'LudoTimer'. Did you forget a ';'?
What gives!
| Have a look in the other header (LudoCore/Singleton.h). The second error implies that the error is before the class LudoTimer declaration at the top.
My guess is that Singleton.h defines a class, and there's a missing ';' after that class definition.
|
1,691,395 | 1,691,624 | How to statically link using link.exe | I've been trying to statically link against a C++ library called Poco on Windows using the Visual Studio 2008 command line tools.
I build my program with:
cl /I..\poco\lib /c myapp.cpp
link /libpath:..\poco\lib myapp.obj PocoNet.lib
This results in an exe that at runtime requires PocoNet.dll and PocoFoundation.dll.
I spent some time reading up on linking in Windows, and learned that cl /MT statically links against the standard library, while cl /MD links dynamically.
I tried to specify /MT, but that didn't seem to change anything; my app still requires the Poco DLLs. (I also suspect that /MT is the default behavior.)
Looking under ..\poco\lib, I found there was also a PocoNetmt.lib, but specifying that instead of PocoNet.lib resulted in a bunch of LNK2005 errors ("already defined"):
msvcprt.lib(MSVCP90.dll) : error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)" (??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) already defined in exp.obj
I then tried stacking on more flags:
/verbose:lib: useful for seeing what's happening
/Zl: same results as before
/nodefaultlib:libcmt.lib /nodefaultlib:msvcprt.lib: got this error:
PocoFoundationmt.lib(Exception.obj) : warning LNK4217: locally defined symbol ??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ (public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)) imported in function __ehhandler$??0Exception@Poco@@QAE@ABV01@@Z
dropping the .lib altogether, as suggested here: same error as above
I also tried some combinations of the above, all to no avail.
Any clues would be greatly appreciated. But just as useful would be any pointers to resources that are useful for debugging (or learning about) these types of issues.
| You have to define POCO_STATIC on the command line and link with both PocoFoundationmt and PocoNetmt.lib:
C:\test>cl /MD /WX /nologo /EHsc /DPOCO_STATIC /DUNICODE /D_UNICODE /I..\poco\Foundation\include /I ..\poco\Net\include /c exp.cpp
exp.cpp
C:\test>link /libpath:..\poco\lib /WX /nologo exp.obj PocoNetmt.lib PocoFoundationmt.lib
[UPDATE]
If you compile with /DPOCO_STATIC, then it isn't necessary to specify the POCO libraries on the linker command line. The header files contain #pragma comment(lib, "PocoXXXmt.lib") statements that should ensure that all the necessary libraries will be linked in.
If you don't compile with /DPOCO_STATIC, then the DLL import libraries will be automatically linked instead.
[/UPDATE]
|
1,691,473 | 1,691,506 | Somehow register my classes in a list | I would like to be able to register my classes within a std::map or a vector, don't think about duplicates and such for now,
but I don't want to register it within the class constructor call or any within function of the class, somehow do it outside the class so even if I never instantiate it, I would be able to know that it exists.
Example:
// Somehow, from outside the myclass, in a scope that will be called
//in the begining of the proccess, add "MyClass1" to a
//list so it can be instanciated later
class MyClass1{
}
Then I would make a #define of it or if able, a template.
I don't know if I made myself clear(again)...
My point is that I need to know every class that I have without having to call every and each of them.
My idea was to create a #define to make it easier to declare the header of the class and call something that would register that specific class to a list
Can this be done or will I have to map it manually?
// desirable:
#define CLASSREGISTER(myclass) makethemagic(##myclass); class myclass {
};
I know, with that define I couldn't use inheritance etc... My point was to try to give an example of what I was thinking to create somehow...
| Here is method to put classes names inside a vector. Leave a comment if I missed important details. I don't think it will work for templates, though.
struct MyClasses {
static vector<string> myclasses;
MyClasses(string name) { myclasses.push_back(name); }
};
#define REGISTER_CLASS(cls) static MyClasses myclass_##cls(#cls);
struct XYZ {
};
REGISTER_CLASS(XYZ);
The trick here is to make some computation before main() is called and you can achieve this via global initialization. REGISTER_CLASS(cls) actually generates code to call the constructor of MyClasses at program startup.
UPDATE: Following gf suggestion you can write this:
#define REGISTER_CLASS(cls) temp_##cls; static MyClasses myclass_##cls(#cls); class cls
class REGISTER_CLASS(XYZ) { int x, y, z; }
|
1,691,491 | 1,691,558 | how to build a vector of different objects after reading a file | everyone! I am new for C++ and now work on a C++ project.The whole structure has been completed.But I have been wondering about
how to build the vector of different objects and how to read the file since the beginning.
In my problem, first I have to read a txt file with readObstacles(std::istream &fs) that has the following format:
RECTANGLE 1 2.5 2 2 0.2
CIRCLE 1 2.5 1.2
RECTANGLE 4 2 2 2 0.3
(each obstacle begins a new line)
I need to read the data information of different obstacles and store these obstacles in a vector.
Class Obstacle is the base class with two sub-classes CIRCLE and RECTANGLE.
I try to put the these different obstacles (that i think should have their data info) in a obstacle vector and then call the virtual function they both have.
Below is the code I try to do with:
vector<Obstacle> obsdata;
Myworld::readObstacles(std::istream &fs)
{
std::string shape;
double num1,num2,num3,num4,num5;
while(fs>>shape>>num1>>num2>>num3>>num4>>num5)
{
if(shape=="CIRCLE") {
CIRCLE c;
c.m_Xc=num1;
c.m_Yc=num2;
c.m_Radius=num3;
obsdata.push_back(c);
}
if(shape=="RECTANGLE") {
RECTANGLE r;
r.center_x=num1;
r.center_y=num2;
r.width=num3;
r.height=num4;
r.angle=num5;
obsdata.push_back(r);
}
}
}
MyWorld::writeMatlabDisplayCode(std::ostream &fs)
{
for( i = 0; i < obsdata.size(); i++ )
obsdata[i].writeMatlabDisplayCode(fs);
}
I know it doesn't work but i don't know what i should do.
Any words will help. Thanks !
| You could try just reading the whole line at a time then tokenize the values...
vector<Obstacle*> obsdata;
string line;
while(getline(fs, line)) {
char *token = strtok(line.c_str(), " ");
string shape(token);
vector<double> numbers;
stringstream ss;
while(token = strtok(NULL, " ")) {
double d;
ss << token;
ss >> d;
numbers.push_back(d);
}
if(shape == "CIRCLE") {
CIRCLE *c = new CIRCLE();
c->m_Xc=numbers[0];
c->m_Yc=numbers[1];
c->m_Radius=numbers[2];
obsdata.push_back(c);
} else if(shape == "RECTANGLE") {
RECTANGLE *r = new RECTANGLE();
r->center_x=numbers[0];
r->center_y=numbers[1];
r->width=numbers[2];
r->height=numbers[3];
r->angle=numbers[4];
obsdata.push_back(r);
}
}
I would delete this vector of pointers in your MyWorld destructor:
~MyWorld() {
// loop thanks to gf
for(std::vector<Obstacle*>::iterator it = obsdata.begin(); it != obsdata.end(); ++it)
delete *it;
}
|
1,691,609 | 3,670,717 | Using Qt to make an almost native Windows Application? | I love that Qt is cross-platform but I want to make an application that will call into some Windows specific .dll's. Kinda like Google Chrome does with the glass on Windows Vista/7 (I know Chrome isn't written using the Qt framework just thought it was a good example).
How can I do this in Qt? Is it feasible?
| You can of course call WinAPI functions directly from your Qt code, then it's better to include qt_windows.h not windows.h.
If you just want to add the cool new Windows 7 features to your application then you are better of using a dedicated Qt add-on. There is one called Q7Goodies.
|
1,691,759 | 1,691,849 | What questions should an expert in STL be expected to answer, in an interview | I was looking at a job posting recently and one of the requirements was that a person be a 9/10 in their knowledge of STL.
When I judge my skills, to me a 10 is someone that writes advanced books on the subject, such as Jon Skeet (C#), John Resig (JavaScript) or Martin Odersky (Scala).
So, a 9/10 is basically a 10, so I am not certain what would be expected at that level.
An example of some questions would be found at: http://discuss.joelonsoftware.com/default.asp?joel.3.414500.47
Obviously some coding will be needed, but should everything be expected to be memorized, as there is quite a bit in STL.
In some cases Boost libraries extend STL, so should it be expected that I would be using Boost also, as I may sometimes confuse which function came from which of the two libraries.
I am trying to get an idea if I can answer questions that would be expected of a STL expert, though it is odd that being a C++ expert wasn't a requirement.
UPDATE
After reflecting on the answers to my question it appears that what they may be looking for is someone that can see the limits of STL and extend the library, which is something I haven't done. I am used to thinking within the limits of what STL and Boost give me and staying within the lines. I may need to start looking at whether that has been too limiting and see if I can go outside the box. I hope they don't mean a 9 as Google does. :)
| Funny -- I don't consider myself a 9/10 in STL (I used to be, but I'm a bit rusty now), and I do fully agree with @joshperry's important terminological distinguo (I've often been on record as berating the abuse of STL to mean "the parts of the C++ standard library that were originally inspired by SGI's STL"!-), yet I consider his example code less than "optimally STL-ish". I mean, for the given task "Put all the integers in a vector to standard out.", why would anyone ever code, as @joshperry suggests,
for(std::vector<int>::iterator it = intVect.begin(); it != intVect.end(); ++i)
std::cout << *it;
rather than the obvious:
std::copy(intVect.begin(), intVect.end(), std::ostream_iterator<int>(std::cout));
or the like?! To me, that would kind of suggest they don't know about std::ostream_iterator -- especially if they're supposed to be showing off their STL knowledge, why wouldn't they flaunt it?-)
At my current employer, to help candidates self-rate about competence in a technology, we provide a helpful guide -- "10: I invented that technology; 9: I wrote THE book about it" and so on down. So, for example, I'd be a 9/10 in Python -- only my colleague and friend Guido can fairly claim a 10/10 there. STL is an interesting case: while Stepanov drove the design, my colleague Matt Austern did the first implementation and wrote "the" book about it, too (this one) -- so I think he'd get to claim, if not a 10, a 9.5. By that standard, I could be somewhere between 7 and 8 if I could take an hour to refresh (custom allocators and traits are always tricky, or at least that's how I recall them!-).
So, if you're probing somebody who claims a 9, grill them over the really hard parts such as custom allocators and traits -- presumably they wouldn't miss a beat on all the containers, algorithms, and special iterators, so don't waste much interview time on those (which would be key if you were probing for a 7 or 7.5). Maybe ask them to give a real-life example where they used custom traits and/or allocators, and code all the details of the implementation as well as a few sample uses.
BTW, if you're the one needing to cram on C++'s standard library at an advanced level, I'm told by knowledgeable and non-rusty friends that Josuttis' book nowadays is even more useful than my friend Matt's (unfortunately, I've never read Josuttis in depth, so I can't confirm or deny that - I do see the book has five stars on Amazon, which is impressive;-).
|
1,692,084 | 1,692,966 | How Non-Member Functions Improve Encapsulation | I read Scott Meyers' article on the subject and quite confused about what he is talking about. I have 3 questions here.
Question 1
To explain in detail, assume I am writing a simple vector<T> class with methods like push_back, insert and operator []. If I followed Meyers' algorithm, I would end up with all non-member friend functions. I will have a vector class with few private members and many non-member friend functions. Is this what he is talking about?
Question 2
I am still not understanding how non-member functions improve encapsulation. Consider the code given in Meyers' article.
class Point {
public:
int getXValue() const;
int getYValue() const;
void setXValue(int newXValue);
void setYValue(int newYValue);
private:
... // whatever...
};
If his algorithm is followed, setXXXX methods should be non-members. My question is how that increases encapsulation? He also says
We've now seen that a reasonable way
to gauge the amount of encapsulation
in a class is to count the number of
functions that might be broken if the
class's implementation changes.
Until we keep the method signature intact when class implementation changes, no client code is gonna break and it is well encapsulated, right? The same applies for non-member functions as well. So what is the advantage non-member function provides?
Question 3
Quoting his algorithm
else if (f needs type conversions
on its left-most argument)
{
make f a non-member function;
if (f needs access to non-public
members of C)
make f a friend of C;
}
What he meant by f needs type conversions on its left-most argument?
He also says the following in the article.
Furthermore, we now see that the
common claim that "friend functions
violate encapsulation" is not quite
true. Friends don't violate
encapsulation, they just decrease it —
in exactly the same manner as a member
functions.
This and the above algorithm are contradictory, right?
| Question 1
In this case, following Meyers's algorithm will give you member functions:
Do they need to be virtual? No.
Are they operator<< or operator>>? No.
Do they need type conversions? No.
Can they be implemented in terms of the public interface? No.
So make them members.
His advice is to only make them friends when they really need to be; to favour non-member non-friends over members over friends.
Question 2
The SetXXXX functions need to access the internal (private) representation of the class, so they can't be non-member non-friends; so, Meyers argues, they should be members rather than friends.
The encapsulation comes about by hiding the details of how the class is implemented; you define a public interface separately from a private implementation. If you then invent a better implementation, you can change it without changing the public interface, and any code using the class will continue to work. So Meyers's "number of functions which might be broken" counts the member and friend functions (which we can easily track down by looking at the class definition), but not any non-member non-friend functions using the class through its public interface.
Question 3
This has been answered.
The important points to take away from Meyers's advice are:
Design classes to have clean, stable public interfaces separate from their private implementation;
Only make functions members or friends when they really need to access the implementation;
Only make functions friends when they can't be members.
|
1,692,156 | 1,692,167 | Erasing a vector element by key | ive defined the following and filled it with elements:
vector <vector<double> > my_vector;
but i want a delete an element with a specific key...
my_vector.erase(int(specific_key));
but it doesnt allow me. how would i properly dispose of the elements assigned to that key properly?
| Assuming by specific_key you mean the element at that position in the vector:
my_vector.erase(my_vector.begin() + specific_key);
Would be the "most correct" answer.
If you meant to delete the element that matches specific_key (which will have to be of type vector<double> in the given example:
my_vector.erase(find(my_vector.begin(), my_vector.end(), specific_key));
|
1,692,184 | 1,692,210 | Converting epoch time to "real" date/time | What I want to do is convert an epoch time (seconds since midnight 1/1/1970) to "real" time (m/d/y h:m:s)
So far, I have the following algorithm, which to me feels a bit ugly:
void DateTime::splitTicks(time_t time) {
seconds = time % 60;
time /= 60;
minutes = time % 60;
time /= 60;
hours = time % 24;
time /= 24;
year = DateTime::reduceDaysToYear(time);
month = DateTime::reduceDaysToMonths(time,year);
day = int(time);
}
int DateTime::reduceDaysToYear(time_t &days) {
int year;
for (year=1970;days>daysInYear(year);year++) {
days -= daysInYear(year);
}
return year;
}
int DateTime::reduceDaysToMonths(time_t &days,int year) {
int month;
for (month=0;days>daysInMonth(month,year);month++)
days -= daysInMonth(month,year);
return month;
}
you can assume that the members seconds, minutes, hours, month, day, and year all exist.
Using the for loops to modify the original time feels a little off, and I was wondering if there is a "better" solution to this.
| Be careful about leap years in your daysInMonth function.
If you want very high performance, you can precompute the pair to get to month+year in one step, and then calculate the day/hour/min/sec.
A good solution is the one in the gmtime source code:
/*
* gmtime - convert the calendar time into broken down time
*/
/* $Header: gmtime.c,v 1.4 91/04/22 13:20:27 ceriel Exp $ */
#include <time.h>
#include <limits.h>
#include "loc_time.h"
struct tm *
gmtime(register const time_t *timer)
{
static struct tm br_time;
register struct tm *timep = &br_time;
time_t time = *timer;
register unsigned long dayclock, dayno;
int year = EPOCH_YR;
dayclock = (unsigned long)time % SECS_DAY;
dayno = (unsigned long)time / SECS_DAY;
timep->tm_sec = dayclock % 60;
timep->tm_min = (dayclock % 3600) / 60;
timep->tm_hour = dayclock / 3600;
timep->tm_wday = (dayno + 4) % 7; /* day 0 was a thursday */
while (dayno >= YEARSIZE(year)) {
dayno -= YEARSIZE(year);
year++;
}
timep->tm_year = year - YEAR0;
timep->tm_yday = dayno;
timep->tm_mon = 0;
while (dayno >= _ytab[LEAPYEAR(year)][timep->tm_mon]) {
dayno -= _ytab[LEAPYEAR(year)][timep->tm_mon];
timep->tm_mon++;
}
timep->tm_mday = dayno + 1;
timep->tm_isdst = 0;
return timep;
}
|
1,692,188 | 1,692,200 | Dynamic Memory Allocation in C++ | What is the difference between the 'delete' and 'dispose' C++ operators with regards to dynamic memory allocation?
| delete will free memory dynamically allocated in unmanaged C++
Dispose will force custom object implemented maintenance of disposable objects in managed C++/CLI
|
1,692,300 | 1,692,338 | Aligning a class to a class it inherits from? Force all stack alignment? Change sizeof? | I want to have a base class which dictates the alignment of the objects which inherit from it. This works fine for the heap because I can control how that gets allocated, and how arrays of it get allocated in a custom array template. However, the actual size of the class as far as C++ is concerned doesn't change at all. Which is to say if I perform pointer arithmetic on a pointer of the derived class then it will skip to the wrong location. That's issue one.
Issue two is stack alignment. There doesn't seem to be a way to directly force the entire stack to be 16 byte aligned pointers.
The only thing I can see to affect these at all is the vc++ and g++ compiler specific settings, but the problem here is I don't want to have to manually fix the alignment all the time. That would be bound to be error prone, not to mention a pain.
I could also maybe make some kind of smart pointer but that would introduce more issues, too.
If I just align the base class, will the child classes be aligned, as well? If so, that would solve most of my problems but that seems doubtful to be the case (though I will try this).
| If a base class has a particular alignment requirement, then any derived classes will have at least that alignment (they could get a stricter alignment requirement due to their own members). Otherwise the compiler couldn't guarantee that accessing the base members would meet the requirements they have.
However, there's really nothing you can portably do for stack alignment - that's handled entirely by the compiler and the compiler's platform ABI requirements. As you indicate, a compiler option or maybe a pragma might let you exert some control, but nothing portable.
|
1,692,319 | 1,692,328 | Declaration inside if/switch | I'm trying to do something like this in C++:
if(){
int a;
} else if(){
char a;
} else {
double a;
}
f(a);
But I get an error from the compiler saying that a was not declared in this scope.
I need to do a conditional declaration, how can I do it?
Many thanks
edit:
I cannot move the function inside the conditional as the problem is bigger:
f(a,b,c);
where a, b and c need to be declared in this way.
| It appears that you want different overloads to be called depending on the path taken through the conditional structure. This is not possible in a static language like C++ because the compiler needs to decide which overload to call at compile time, and can only pick one for each call.
Do this instead:
if (...) {
int a = ...;
f(a);
} else if (...) {
char a = ...;
f(a);
} else {
double a = ...;
f(a);
}
|
1,692,418 | 1,692,860 | How to solve linear equations using a genetic algorithm? | I want to solve a system of n linear equations containing n variables using a genetic algorithm.
I am having difficulty in defining the crossover operation as the solution may consist of floating point values. How do I proceed? It seems possible, but this is my first encounter with genetic algorithms.
Suppose we have to solve
x + 2y = 1
2x + 8y = 3
The answer would be x = 1/2 and y = 1/4.
How do we model the problem?
Update: see if you could decipher anything from the paper http://www.masaumnet.com/archives/mjbas/volume1/issue2/mjbas010205.pdf.
| One route is to pick your own floating point representation, which frees you to much with values as you want. Of course, that makes you responsible for implementing arithmetic operations. Perhaps you could find a bignum library you could alter.
You could also decompose platform-native floating points using e.g. frexp during the crossover step, then recombine it during culling.
|
1,692,680 | 1,692,724 | Compiling a shared library with Qt on Ubuntu 9.10 | I am new to both Qt and Linux C++ development (although I have many years C and C++ development experience on Windows).
I have some legacy C projects (source files and headers - [not using Qt]) that I want to compile into shared libs on Linux.
I am proposing to store my projects under the following structure:
/home/username/Projects/project_name
/home/username/Projects/project_name/src
/home/username/Projects/project_name/build
Can anyone tell me how to do the following (using Qt to simplify the build process)
Create different build configurations (debug, release etc)
Build a configuration to create the appropriate shared library
As an aside, I have only recently installed Ubuntu 9.10 and the only C/C++ development tool I have installed (using SPM) in Qt - so I dont know if I need to install some other GNU C++ tools.
BTW I have already checked and have gcc (v4.4.1) available on my machine. I do not appear to have g++ though - I do not know whether this is significant or not.
| An Ubuntu system doesn't come with build tool chain by default. Instead it has a meta package that you will need to install:
sudo apt-get install build-essential
This will install, among other the g++ compiler, although I am not sure about the Qt headers an such. For them you will need the qt4-dev package (I assume you wish to work with qt4 rather then qt3).
As for the bould structure, you will want to consult the qmake manual, or you might want to consider using CMake (apt-get install cmake) instead. CMake allow for out of build sources, as you require, and personally, I can't recommend it enough.
|
1,693,042 | 1,693,068 | How do STL containers copy objects? | I know STL containers like vector copies the object when it is added. push_back method looks like:
void push_back ( const T& x );
I am surprised to see that it takes the item as reference. I wrote a sample program to see how it works.
struct Foo
{
Foo()
{
std::cout << "Inside Foo constructor" << std::endl;
}
Foo(const Foo& f)
{
std::cout << "inside copy constructor" << std::endl;
}
};
Foo f;
std::vector<Foo> foos;
foos.push_back(f);
This copies the object and I can see it is calling copy-constructor.
My question is, when the push_back takes item as reference, how it is calling copy-constructor? Or am I missing something here?
Any thoughts..?
| It probably uses "placement new" to construct the object in-place in its internal array. Placement new doesn't allocate any memory; it just places the object where you specify, and calls the constructor. The syntax is new (address) Class(constructor_arguments).
The copy constructor T::T(T const &) is called to create the copy in-place. Something like this (simplified):
template<T>
void vector<T>::push_back(T const &item) {
// resize if necessary
new (&d_array[d_size++]) T(item);
}
Note that T must have a copy constructor for this to work. By default (if you do nothing), it gets one for free. If you define it explicitly, it must be public for vector<T> to work.
Here's how GNU's libstdc++ does it, but I doubt that it'll be very enlightening. There is an allocator (the second template argument to vector) that makes it less straightforward.
|
1,693,089 | 1,693,123 | Fastest way to write large STL vector to file using STL | I have a large vector (10^9 elements) of chars, and I was wondering what is the fastest way to write such vector to a file. So far I've been using next code:
vector<char> vs;
// ... Fill vector with data
ofstream outfile("nanocube.txt", ios::out | ios::binary);
ostream_iterator<char> oi(outfile, '\0');
copy(vs.begin(), vs.end(), oi);
For this code it takes approximately two minutes to write all data to file. The actual question is: "Can I make it faster using STL and how"?
| There is a slight conceptual error with your second argument to ostream_iterator's constructor. It should be NULL pointer, if you don't want a delimiter (although, luckily for you, this will be treated as such implicitly), or the second argument should be omitted.
However, this means that after writing each character, the code needs to check for the pointer designating the delimiter (which might be somewhat inefficient).
I think, if you want to go with iterators, perhaps you could try ostreambuf_iterator.
Other options might include using the write() method (if it can handle output this large, or perhaps output it in chunks), and perhaps OS-specific output functions.
|
1,693,098 | 1,693,293 | How dynamic casts work? | Let's say I have type A, and a derived type B. When I perform a dynamic cast from A* to B*, what kind of "runtime checks" the environment performs? How does it know that the cast is legal?
I assume that in .Net it's possible to use the attached metadata in the object's header, but what happen in C++?
| Exact algorithm is compiler-specfic. Here's how it works according to Itanium C++ ABI (2.9.7) standard (written after and followed by GCC).
Pointer to base class is a pointer to the middle of the body of the "big" class. The body of a "big" class is assembled in such a way, that whatever base class your pointer points to, you can uniformly access RTTI for that "big" class, which your "base" class in fact is. This RTTI is a special structure that relates to the "big" class information: of what type it is, what bases it has and at what offsets they are.
In fact, it is the "metadata" of the class, but in more "binary" style.
V instance;
Base *v = &instance;
dynamic_cast<T>(v);
Dynamic cast makes use of the fact that when you write dynamic_cast<T>(v), the compiler can immediately identify metadata for the "big" class of v -- i.e. V! When you write it, you think that T is more derived than Base, so compiler will have hard time doing base-to-drived cast. But compiler can immediately (at runtime) determine most deirved type--V--and it only has then to traverse the inheritance graph contained in metadata to check whether it can downcast V to T. If it can, it just checks the offset. If it can't or is amboguous -- returns NULL.
|
1,693,134 | 1,693,160 | Declaring an array whose size is declared as extern const | I have a problem initializing an array whose size is defined as extern const.
I have always followed the rule that global variables should be declared as extern in the header files and their corresponding definitions should be in one of the implementation files in order to avoid variable redeclaration errors. This approach worked fine till I had to initialize an array with whose size is defined as an extern const.
I get an error that a constant expression is expected. However, if I try to assign a value to the const variable the compiler correctly complains that a value cannot be assigned to a constant variable. This actually proves that the compiler does see the variable as a constant. Why then is an error reported when I try to declare an array of the same size?
Is there any way to avoid this without using #define? I would also like to know the reason for this error.
Package.h:
#ifndef PACKAGE_H
#define PACKAGE_H
extern const int SIZE;
#endif
Package.cpp:
#include "Package.h"
const int SIZE = 10;
Foo.cpp:
#include "Package.h"
int main()
{
// SIZE = 5; // error - cannot assign value to a constant variable
// int Array[SIZE]; // error - constant expression expected
return 0;
}
| The constant is external, so it is defined in another compilation unit (.o file). Therefore the compiler cannot determine the size of your array at compilation time; it is not known until link time what the value of the constant will be.
|
1,693,336 | 1,693,348 | Overloading both operator< and operator> in the same class | In my homework, I have to design a class Message; among other attributes, it has attribute "priority" (main goal is to implement priority queue).
As in container I must check if one object is greater than other, I have overloaded operator '>'. Now, I have a few general questions about it...
Question one:
If I overload operator '>', should I overload operator '<' for arguments (const Message&, const Message&)?
My opinion is that overloading both > and < and using it in code will generate an error:
if(message1 > message2)
{ ... }
(Does the following code calls operator > for message1 object, or operator < message2 object?)
But, what if I use operator like this:
if(message1 < message2)
{ ... }
?
operator> is declared as friend function:
friend bool operator>(const Message& m1, const Message& m2)
Does it need to be declared as member function?
Thank you.
|
If I overload operator '>', should I overload operator '<' for argumenst (const Message&, const Message&)?
Yes. In fact, it’s convention in most code to prefer the usage of < over > (don’t ask me why, probably historical). But more generally, always overload the complete set of related operators; in your case, this would probably also be ==, !=, <= and >=.
(Does the following code calls operator > for message1 object, or operator < message2 object?)
It always calls what it finds in the code. For the C++ compiler, there’s absolutely no connection between > and <. For us, they look similar but the compiler sees two completely different, unrelated symbols. So there’s no ambiguity: the compiler calls what it sees.
Does it need to be declared as member function?
No. In fact, it’s best not declared as a member function. Declaring it as a member function means that the first argument (i.e. the left-hand side of the expression) must really be a Message object, rather than an object that is implicitly convertible to a Message.
To understand this, consider the following case:
struct RealFraction {
RealFraction(int x) { this.num = x; this.den = 1; }
RealFraction(int num, int den) { normalize(num, den); }
// Rest of code omitted.
bool operator <(RealFraction const& rhs) {
return num * rhs.den < den * rhs.num;
}
};
Now you can write the following comparison:
int x = 1;
RealFraction y = 2;
if (y < x) …
but you cannot write the following:
if (x < y) …
although there exists an implicit conversion from int to RealFraction (using the first constructor).
If, on the other hand, you had used a non-member function to implement the operator, both comparisons would work because C++ would know to call an implicit constructor on the first argument.
|
1,693,345 | 1,693,355 | Tool for program statistics | Is there a tool which is able to parse my source code (fortran, C or C++) and return statistics such as the number of loops, the average loop size, the number of functions, the number of function calls, the number, size and type of arrays, variables, etc ?
Something similar to this which does not run easily on my architecture
| The magic Google term is "code metrics". Wikipedia has a list.
|
1,693,523 | 2,458,711 | StAX Writer Implementation for C/C++ | Are there any other STaX Writer implementation for C/C++ except libxml2?
| LLamaXML
Its one of the few C++ pull parsers.
|
1,693,579 | 1,693,591 | Bitflag enums in C++ | Using enums for storing bitflags in C++ is a bit troublesome, since once the enum values are ORed they loose their enum-type, which causes errors without explicit casting.
The accepted answer for this question suggests overloading the | operator:
FlagsSet operator|(FlagsSet a, FlagsSet b)
{
return FlagsSet(int(a) | int(b));
}
I'd like to know if this method has any runtime implications?
| Runtime implications in terms of correctness? No - this should be exactly what you want.
Runtime implications in terms of speed? I would expect any decent compiler to optimize this away properly to the minimal number of instructions for a release build (although you might want to add inline just to be sure).
|
1,693,615 | 1,693,643 | What are the best RSS feeds for C++? | What are the best RSS feeds for C++ ?
| This post lists C++ blogs, most of those blogs have rss feeds.
Also...don't forget the rss feed for the Stackoverflow C++ tag!
|
1,693,871 | 1,693,901 | Problem with priority_queue - Writing memory after heap | I am trying to use priority_queue, and program constantly fails with error message HEAP CORRUPTION DETECTED.
here are the snippets:
class CQueue { ...
priority_queue<Message, deque<Message>, less<deque<Message>::value_type> > m_messages;
...};
class Message has overloaded operators > and <
Here I fill up queue:
CQueue & operator+=(Message &rhv)
{
m_messages.push(rhv); //This is where program fails
return *this;
}
and in the main program:
string str;
CQueue pq;
for(int i = 0; i < 12; ++i)
{
cin >> str;
Message p(str.c_str(), rand()%12); //Create message with random priority
pq += p; //add it to queue
}
I have no idea what seems to be the problem. It happens when I push about 8 items, and it fails on line
push_heap(c.begin(), c.end(), comp);
in < queue >
:(
Here is the definition of message class - it's very simple:
#pragma once
#include <iostream>
#include <cstring>
#include <utility>
using namespace std;
class Poruka
{
private:
char *m_tekst;
int m_prioritet;
public:
Poruka():m_tekst(NULL), m_prioritet(-1){}
Poruka(const char* tekst, const int prioritet)
{
if(NULL != tekst)
{
// try{
m_tekst = new char[strlen(tekst) + 1];
//}
//catch(bad_alloc&)
// {
// throw;
// }
strcpy(m_tekst, tekst);
}
else
{
// try
// {
m_tekst = new char[1];
// }
// catch(bad_alloc&)
// {
// throw;
// }
m_tekst[0] = '\0';
}
m_prioritet = prioritet;
}
Poruka(const Poruka &p)
{
if(p.m_tekst != NULL)
{
//try
//{
m_tekst = new char[strlen(p.m_tekst) + 1];
//}
//catch(bad_alloc&)
//{
// throw;
//}
strcpy(m_tekst, p.m_tekst);
}
else
{
m_tekst = NULL;
}
m_prioritet = p.m_prioritet;
}
~Poruka()
{
delete [] m_tekst;
}
Poruka& operator=(const Poruka& rhv)
{
if(&rhv != this)
{
if(m_tekst != NULL)
delete [] m_tekst;
// try
//{
m_tekst = new char[strlen(rhv.m_tekst + 1)];
//}
//catch(bad_alloc&)
//{
// throw;
//}
strcpy(m_tekst, rhv.m_tekst);
m_prioritet = rhv.m_prioritet;
}
return *this;
}
friend ostream& operator<<(ostream& it, const Poruka &p)
{
it << '[' << p.m_tekst << ']' << p.m_prioritet;
return it;
}
//Relacioni operatori
friend inline bool operator<(const Poruka& p1, const Poruka& p2)
{
return p1.m_prioritet < p2.m_prioritet;
}
friend inline bool operator>(const Poruka& p1, const Poruka& p2)
{
return p2 < p1;
}
friend inline bool operator>=(const Poruka& p1, const Poruka& p2)
{
return !(p1 < p2);
}
friend inline bool operator<=(const Poruka& p1, const Poruka& p2)
{
return !(p1 > p2);
}
friend inline bool operator==(const Poruka& p1, const Poruka& p2)
{
return (!(p1 < p2) && !(p2 < p1));
}
friend inline bool operator!=(const Poruka& p1, const Poruka& p2)
{
return (p1 < p2) || (p2 < p1);
}
};
Poruka - Message
| I think the problem is that your Message objects are keeping pointers to raw C strings which are then getting deallocated. In these lines:
cin >> str;
Message p(str.c_str(), rand()%12);
On each iteration of the loop, you're reading in a new value to str, which invalidates any old pointers returned by its c_str() method, so your older messages are pointing to invalid data. You should change your Message object so that it stores its string as an std::string instead of a char*. This will properly copy the string into the Message object.
Alternatively, if you can't change the Message class, you'll have to explicitly copy the string yourself, e.g. using strdup() or malloc()/new[]+strcpy(), and then you have to remember to deallocate the string copies at some later point.
|
1,693,908 | 1,693,919 | C++: pass variable by value | This is the situation:
int f(int a){
...
g(a);
...
}
void g(int a){...}
The problem is that the compiler says that there is no matching function for call to g(int&). It wants me to pass the variable by reference and g() recieves parameters by value.
How can I solve this?
| Well, there's not much here, but the first thing is: make sure you have a declaration for g that's included before f is defined.
void g(int a);
Otherwise, when you get to f, function f has no idea what function g looks like, and you'll run into trouble. From what you've given so far, that's the best I can say.
|
1,694,041 | 1,694,099 | Rotating coordinates around an axis | I'm representing a shape as a set of coordinates in 3D, I'm trying to rotate the whole object around an axis (In this case the Z axis, but I'd like to rotate around all three once I get it working).
I've written some code to do this using a rotation matrix:
//Coord is a 3D vector of floats
//pos is a coordinate
//angles is a 3d vector, each component is the angle of rotation around the component axis
//in radians
Coord<float> Polymers::rotateByMatrix(Coord<float> pos, const Coord<float> &angles)
{
float xrot = angles[0];
float yrot = angles[1];
float zrot = angles[2];
//z axis rotation
pos[0] = (cosf(zrot) * pos[0] - (sinf(zrot) * pos[1]));
pos[1] = (sinf(zrot) * pos[0] + cosf(zrot) * pos[1]);
return pos;
}
The image below shows the object I'm trying to rotate (looking down the Z axis) before the rotation is attempted, each small sphere indicates one of the coordinates I'm trying to rotate
alt text http://www.cs.nott.ac.uk/~jqs/notsquashed.png
The rotation is performed for the object by the following code:
//loop over each coordinate in the object
for (int k=start; k<finish; ++k)
{
Coord<float> pos = mp[k-start];
//move object away from origin to test rotation around origin
pos += Coord<float>(5.0,5.0,5.0);
pos = rotateByMatrix(pos, rots);
//wrap particle position
//these bits of code just wrap the coordinates around if the are
//outside of the volume, and write the results to the positions
//array and so shouldn't affect the rotation.
for (int l=0; l<3; ++l)
{
//wrap to ensure torroidal space
if (pos[l] < origin[l]) pos[l] += dims[l];
if (pos[l] >= (origin[l] + dims[l])) pos[l] -= dims[l];
parts->m_hPos[k * 4 + l] = pos[l];
}
}
The problem is that when I perform the rotation in this way, with the angles parameter set to (0.0,0.0,1.0) it works (sort of), but the object gets deformed, like so:
alt text http://www.cs.nott.ac.uk/~jqs/squashed.png
which is not what I want. Can anyone tell me what I'm doing wrong and how I can rotate the entire object around the axis without deforming it?
Thanks
nodlams
| Where you do your rotation in rotateByMatrix, you compute the new pos[0], but then feed that into the next line for computing the new pos[1]. So the pos[0] you're using to compute the new pos[1] is not the input, but the output. Store the result in a temp var and return that.
Coord<float> tmp;
tmp[0] = (cosf(zrot) * pos[0] - (sinf(zrot) * pos[1]));
tmp[1] = (sinf(zrot) * pos[0] + cosf(zrot) * pos[1]);
return tmp;
Also, pass the pos into the function as a const reference.
const Coord<float> &pos
Plus you should compute the sin and cos values once, store them in temporaries and reuse them.
|
1,694,063 | 1,694,069 | Templates and nested classes/structures | I have a simple container :
template <class nodeType> list {
public:
struct node {
nodeType info;
node* next;
};
//...
};
Now, there is a function called _search which searches the list and returns a reference to the node which matched. Now, when I am referring to the return-type of the function, I think it should be list<nodeType>::node*. Is this right? When I define the function inline, it works perfectly:
template <class nodeType> list {
public:
struct node {
nodeType info;
node* next;
};
node* _search {
node* temp;
// search for the node
return temp;
}
};
But, if I define the function outside the class,
template <class nodeType> list<nodeType>::node* list<nodeType>::_search() {
//function
}
it doesn't work. The compiler gives an error saying Expected constructor before list<nodeType>::_search or something. The error is something similar to this. I don't have a machine on which I can test it currently.
Any help is sincerely appreciated.
| that's because node is a dependent type. You need to write the signature as follows (note that I have broken it into 2 lines for clarity)
template <class nodeType>
typename list<nodeType>::node* list<nodeType>::_search()
{
//function
}
Note the use of the typename keyword.
|
1,694,320 | 1,694,333 | how many strings in a const char* str[]? | const static char *g_szTestDataFiles[] = {
".\\TestData\\file1.txt",
".\\TestData\\file2.txt",
".\\TestData\\file3.txt",
".\\TestData\\file4.txt",
".\\TestData\\file5.txt",
".\\TestData\\file6.txt"
};
Is there way to programmatically determine how many items is in that thing? I could always do #define NUM_DATA_FILES 6 or const int NUM_DATA_FILES=6 but is there a better way? I don't think there is, but this seems too basic and I want to make sure i'm not forgetting something . . .
| Arkaitz has given you the preferred way of handling this, but as we're talking about an array of const char * here, you should be able to do the following:
int size = sizeof(g_szTestDataFiles) / sizeof(g_szTestDataFiles[0]);
|
1,694,518 | 1,695,779 | Hiding a QWidget on a QToolbar? | I have directly added some QWidgets to a QToolbar but simply going widget->setVisible(false) did not work. Can someone please give me an example of how to show and hide a widget that is on a QToolbar?
Thanks!
| You need to call setVisible() on the appropriate QAction instead. For example, addWidget() returns a QAction*:
QAction* widgetAction = toolBar->addWidget(someWidget);
widgetAction->setVisible(false);
|
1,694,665 | 1,694,669 | static variable vs. member | If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variable a local static variable of the routine that it is in or make it a member of the class?
| The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.
|
1,694,785 | 1,694,895 | What should I do with this strange error? | Everything is fine and the final problem is so annoying. Compile is great but link fails:
bash-3.2$ make
g++ -Wall -c -g Myworld.cc
g++ -Wall -g solvePlanningProblem.o Position.o AStarNode.o PRM.o PRMNode.o World.o SingleCircleWorld.o Myworld.o RECTANGLE.o CIRCLE.o -o solvePlanningProblem
**Undefined symbols:
"vtable for Obstacle", referenced from:
Obstacle::Obstacle()in Myworld.o
"typeinfo for Obstacle", referenced from:
typeinfo for RECTANGLEin RECTANGLE.o
typeinfo for CIRCLEin CIRCLE.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [solvePlanningProblem] Error 1**
Obstacle.hh
#ifndef Obstacle_hh
#define Obstacle_hh
#include <vector>
#include <iostream>
class Obstacle{
public:
Obstacle(){}
virtual bool collidesWith(double x,double y);
virtual void writeMatlabDisplayCode(std::ostream &fs);
virtual ~Obstacle(){}
};
#endif
What's the problem I have ? I can post any code you need to analyze it.
| You declare a non-abstract class Obstacle, but you don't implement all its member functions.
Better declare it as abstract class:
class Obstacle{
public:
Obstacle(){} // this is superfluous, you can (and should) remove it
virtual bool collidesWith(double x,double y) = 0;
virtual void writeMatlabDisplayCode(std::ostream &fs) = 0;
virtual ~Obstacle(){}
};
The reason is a heuristic you'll find in many C++ compilers - to avoid the needless creation of duplicate vtables and typeinfos for a class they are created when its first non-inline virtual member function (if it has one) is defined.
Your code foils this scheme: You include Obstacle.hh into some compilation unit, the compiler sees a class Obstacle that has collidesWith as first non-inline virtual member function, but it isn't defined in the current compilation unit, so the compiler thinks it can defer the creation of vtable and typeinfo for the class. Because there is no definition of collidesWith, they both end up missing when the program is linked.
|
1,694,798 | 1,694,807 | C++ error converting a string to a double | I am trying to convert a string to a double. The code is very simple.
double first, second;
first=atof(str_quan.c_str());
second=atof(extra[i+1].c_str());
cout<<first<<" "<<second<<endl;
quantity=first/second;
when trying to convert extra, the compiler throws this gem of wisdom at me:
error: request for member c_str in
extra.std::basic_string<_CharT,
_Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits, _Alloc =
std::allocator](((unsigned
int)(i + 1))), which is of non-class
type char
I have no idea what that means. if I cout extra[i+1], I get 3. If I leave extra as a string, the program tries to div first (2) by 51 (ascii for 3). What the heck is going on?
| It sounds like extra is a std::string, so extra[i+1] returns a char, which is of non-class type.
It sounds like you are trying to parse the string extra starting from the i+1th position. You can do this using:
second = atof(extra.substr(i + 1).c_str());
|
1,694,902 | 1,695,838 | Hash/key creation function for latitude longitude? | I have blocks of data associated with latitude/longitude values. I'd like to create a lookup key/hash value from the latitude/longitude value so it can be used as a lookup into a map or something similar.
I'm using negative values for West and South... therefore 5W, 10S is represented as -5, -10 in the program.
I'd like to be able to get the latitude/longitude values back from the key value if possible.
The derived value MUST be some sort of integer value.
I'm using C/C++ :)
Thanks, I'll be happy to answer any questions!
| You could also encode it in nicely into a 64-bit integer using some bit manipulation
longitude ranges from -180 to 180 so needs a minimum of 9 bits.
lattitude rangs from -90 to +90 so needs a minimum of 8 bits.
minutes go from 0 to 60 so require 6 bits.
same for seconds.
9+12 = 21 bits for longitude and 20 bits for lattitude.
For subsecond precision you can then use 11 bit fixed point. this gives you accuracy down to a 2048th of a second.
SO to store a longitude or lattitude you could use a struct as follows
struct ALatLong
{
int angle:9;
int minutes:6;
int seconds:6;
int subSeconds:11;
};
struct LatAndLong
{
ALatLong longitude;
ALatLong lattitude;
};
|
1,694,963 | 1,694,981 | Thread-safe, lock-free increment function? | UPDATED: Is there a thread-safe, lock-free and available on all Linux distros increment function available in C or C++ ?
| GLib has functions to do this. You might check out http://library.gnome.org/devel/glib/stable/glib-Atomic-Operations.html
Specifically, it sounds like you want g_atomic_int_inc()
|
1,695,042 | 1,695,087 | Is garbage collection automatic in standard C++? | From what I understand, in standard C++ whenever you use the new operator you must also use the delete operator at some point to prevent memory leaks. This is because there is no garbage collection in C++. In .NET garbage collection is automatic so there is no need to worry about memory management. Is my understanding correct? Thanks.
| The long answer to it is that for every time new is called, somewhere, somehow, delete must be called, or some other deallocation function (depends on the memory allocator etc.)
But you don't need to be the one supplying the delete call:
There is garbage collection for C++, in the form of the Hans-Boehm Garbage Collector. There is also probably other garbage collection libraries.
You can use smart pointers, which use RAII (and reference counting if the pointer allows shared access) to determine when to delete the object. A good smart pointer library is Boost's smart pointer. Smart pointers in the vast majority of cases can replace raw pointers.
Some application frameworks, like Qt, build object trees, such that there is a parent child relationship for the framework's heap allocated objects. As a result, all is needed is for a delete to be called on an object, and all its children will automatically be deleted as well.
If you don't want to use any of these techniques, to safeguard against memory leaks, you can try using a memory checking tool. Valgrind is particularly good, although it only works on Linux
As for .NET, yes, allocating using gcnew means that the memory is tracked by .NET, so no leaks. Other resources however, like file handles etc. are not managed by the GC.
|
1,695,288 | 1,695,296 | Getting the current time (in milliseconds) from the system clock in Windows? | How can you obtain the system clock's current time of day (in milliseconds) in C++? This is a windows specific app.
| To get the time expressed as UTC, use GetSystemTime in the Win32 API.
SYSTEMTIME st;
GetSystemTime(&st);
SYSTEMTIME is documented as having these relevant members:
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
As shf301 helpfully points out below, GetLocalTime (with the same prototype) will yield a time corrected to the user's current timezone.
You have a few good answers here, depending on what you're after. If you're looking for just time of day, my answer is the best approach -- if you need solid dates for arithmetic, consider Alex's. There's a lot of ways to skin the time cat on Windows, and some of them are more accurate than others (and nobody has mentioned QueryPerformanceCounter yet).
|
1,695,303 | 1,695,306 | Private static variables to establish invariants | Is it reasonable to use private static variables to establish invariants in your class?
Ex:
class MovingObject
{
public:
//...Stuff
private:
// Invariants
static const double VELOCITY; // Moving objects always move at this velocity
// etc. for any other invariants
//...
}
---------------------------------------------------------------------------------
#include "MovingObject.h"
// Invariants
const double MovingObject::VELOCITY = 256.5;
//etc.
| Sure. This is a common idiom across several OO languages including Java.
|
1,695,389 | 1,695,544 | Odd behavior of mktime() | Continuing on my attempt to create a DateTime class , I am trying to store the "epoch" time in my function:
void DateTime::processComponents(int month, int day, int year,
int hour, int minute, int second) {
struct tm time;
time.tm_hour = hour;
time.tm_min = minute;
time.tm_sec = second;
time.tm_mday = day;
time.tm_mon = month;
time.tm_year = year - 1900;
ticks_ = mktime(&time);
processTm(time);
}
void DateTime::processTm(struct tm time) {
second_ = time.tm_sec;
minute_ = time.tm_min;
hour_ = time.tm_hour;
weekday_ = time.tm_wday;
monthday_ = time.tm_mday;
yearday_ = time.tm_yday;
month_ = time.tm_mon;
year_ = time.tm_year + 1900;
}
For an arbitrary date, processComponents(5,5,1990,1,23,45) (June 6, 1990 1:23:45 am), it sets all values correctly and as expected.
However, upon further testing, I find that for processComponents(0,0,1970,0,0,0) (January 1, 1970, 12:00:00 am), mktime(&time) causes time to be screwed up:
time.tm_mon = 11;
time.tm_mday = 30;
time.tm_year = 69;
time.tm_hour = 23;
time.tm_min = 0;
time.tm_sec = 0;
time.tm_isdst = 0;
time.tm_gmtoff = -18000;
time.tm_zone = "EST";
time.tm_wday = 2;
time.tm_yday = 363;
Translating to a date of December 31, 1969 11:00:00 pm.
I can verify that mktime() is responsible, because by commenting out that line, it reports the date and time correctly as January 1, 1970 12:00:00 am.
Why is mktime() only messing up the epoch? And how should I fix / workaround this?
Thanks!
| You're passing 0 as the day parameter and putting that into time.tm_mday. That component (and only that component) of struct tm is 1-based, not 0-based.
Don't ask me why.
To specify 01 Jan 1970, 12:00:00am you'd want to call it like so:
processComponents(0,1,1970,0,0,0);
And as sdtom mentioned, you'll want to make sure that tm_isdst is set appropriately - 0 for not in effect, positive for in effect, and negative for you don't know (in which case mktime() should try to guess).
Just to let you know, when I pass the date you have (0 Jan 1970, 00:00:00) to mktime() in MSVC 9 it returns an error (the passed in struct tm is untouched and the returned time_t value is -1).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.