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 |
|---|---|---|---|---|
2,722,239 | 2,722,325 | Migrating Application Configuration from Windows Registry to SQLite | Currently, I am working on the migration mentioned in the title line. Problem is application configuration that is kept in registry has a tree like structure, for example:
X
|->Y
|->Z
|->SomeKey someValue
W
|->AnotherKey anotherValue
and so on.
How can I model this structure in SQLite (or any other DB)? If ... | Baris, this structure its similar to a directory/file structure.
You can model this with a simple parent<>child relationship on the directories and key value pairs relatade to the directory.
Something like
Directory:
id integer auto_increment;
name string not null;
parent_id integer not null default 0;
Property:
id i... |
2,722,241 | 2,722,367 | List - Strings - Textfiles | I've got a few questions concerning text files,list and strings.
I wonder if it is possible to put in a code which reads the text in a textfile,and then using "string line;" or something else to define each new row of the text and turn all of them into one list. So I can sort the rows, remove a row or two or even all o... | In C++, you'd typically do this with an std::vector:
std::vector<std::string> data;
std::string temp;
while (std::getline(infile, temp))
data.push_back(temp);
Sorting them would then look like:
std::sort(data.begin(), data.end());
Deleting row N would look like:
data.erase(data.begin() + N);
|
2,722,421 | 2,722,623 | how to determine value of cxxflags in bjam? Or append to it? | I need to add to compiler flags using bjam. So either I need a way to append to the existing flags -- like CXXFLAGS+=whatever using gmake -- or I need to know the currently-used value of cxxflags so I can replace it with my additions.
As usual, the documentation leaves me astonished at the complexity of bjam but no clo... | If you are only looking to do this on the command line you can add flags by specifying "feature=value" arguments. In the case of the make CXXFLAGS the corresponding would be "cxxflags=--some-option". Refer to the Boost Build docs section on built-in features for other such possible features to use. If you are using Boo... |
2,722,432 | 2,722,695 | how to implement OOP using QT | this is a simple OOP QT question.
my app consists of main window (QMainWindow) and a table (QTableWidget).
in the main window i have arguments and variables which i would like to pass to the table class, and to access methods in main widnow class from the table class, how should i do it ?
mainwindow.h
class MainWindow ... | You can use the parent() method in the Spreadsheet object to get a pointer to your MainWindow.
For example,
// spreadsheet.cpp
MainWindow* mainWindow = (MainWindow*) this->parent();
mainWindow->set_a(123);
Of course, the parent object passed to Spreadsheet's constructor should be your MainWindow instance for this to w... |
2,722,442 | 2,722,560 | When to choose std::vector over std::map for key-value data? | Considering the positive effect of caching and data locality when searching in primary memory, I tend to use std::vector<> with std::pair<>-like key-value items and perform linear searches for both, if I know that the total amount of key-value items will never be "too large" to severely impact performance.
Lately I've ... | I only rarely use std::vector with a linear search (except in conjunction with binary searching as described below). I suppose for a small enough amount of data it would be better, but with that little data it's unlikely that anything is going to provide a huge advantage.
Depending on usage pattern, a binary search on ... |
2,722,522 | 2,722,549 | why do game engines prefer static libraries over dynamic link libraries | I've been reading a few gaming books. And they always prefer to create the engine as a static library over dynamic link. I am new to c++ so I am not highly knowledge when it comes to static libraries and dynamic link libraries. All I know is static libraries increase the size of your program, where DLL link libraries a... | Dynamic link libraries need to be position independent; this can cause performance inefficiencies on some processor architectures.
Static libraries can be optimized when included in your program, e.g., by stripping dead code. This can improve cache performance.
|
2,722,537 | 2,722,589 | How do virtual destructors work? | Few hours back I was fiddling with a Memory Leak issue and it turned out that I really got some basic stuff about virtual destructors wrong! Let me put explain my class design.
class Base
{
virtual push_elements()
{}
};
class Derived:public Base
{
vector<int> x;
public:
void push_elements(){
for(int i=0;... | Deleting a derived-class object through a base-class pointer when the base class does not have a virtual destructor leads to undefined behavior.
What you've observed (that the derived-class portion of the object never gets destroyed and therefore its members never get deallocated) is probably the most common of many po... |
2,722,650 | 2,722,687 | c++ compilation error | i got a compile error which i do not understand.
i have a h/cpp file combination that does not contain a class but just defines some utility functions. when i try to use a struct that is defined in another class i get the error:
error C2027: use of undefined type 'B::C'
so, stripped down to the problem, the h-file look... | After correcting missing semicolons etc. this compiles:
namespace B {
class C {
public:
struct SStruct { };
};
}
namespace A {
void foo(B::C::SStruct const & Var);
}
Obviously, if the order of the two namespaces were switched, this would not work. Possibly you are #including your headers in... |
2,722,658 | 2,722,684 | What is the best way to expose a callback API - C++ | I have a C++ library that should expose some system\ resource calls as callbacks from the linked application. For example: the interfacing application (which uses this library) can send socket management callback functions - send, receive, open, close etc., and the library will use this implementation in stead of the l... | Why not have it accept a 0 argument functor and just have the user use boost::bind to build the arguments into it before registering it? Basically example (calls instead of stores, but you get the point):
#include <tr1/functional>
#include <iostream>
void callback(const std::tr1::function<int()> &f) {
f();
}
int ... |
2,722,696 | 2,724,055 | Caching XSD schema to reuse in several XML DOM parser tasks in Xerces | How can I cache an XSD schema (residing on disk) to be reused when parsing XMLs in Xerces (C++)?
I would like to load the XSD schema when starting the process, then, whenever I need to parse an XML, to validate it first using this loaded schema.
| I think I found what I need here.
|
2,722,700 | 2,722,745 | How to convert a char* to a string? | When I convert char* to an string it gives an bad memory allocation error in 'new.cpp' . I used following method to convert char* called 'strData' and 'strOrg' to string.
const char* strData = dt.data();
int length2 = dt.length();
string s1(strData);
First time it work without any problem. But in the second c... | Instead of
char * imgData = new char;
is1.read(reinterpret_cast<char *> (imgData), length2);
try
char * imgData = new char[length2];
is1.read(reinterpret_cast<char *> (imgData), length2);
When you read data from an istringstream using read, the buffer you provide must have enough space to hold the results!
If you cal... |
2,722,824 | 2,722,849 | turning a project into a static library | I checked out the microsoft documents. it shows how to create a static library upon creation of the project. but not necessarily on how to convert a previously made project, into a static library. So my question is, where do I go to turn my previously made project, into a static lib. so I can include it in my other pro... | Project | Properties -> Configuration Properties -> General -> Configuration Type (Static Library).
|
2,722,879 | 2,722,898 | Calling constructors in c++ without new | I've often seen that people create objects in C++ using
Thing myThing("asdf");
Instead of this:
Thing myThing = Thing("asdf");
This seems to work (using gcc), at least as long as there are no templates involved. My question now, is the first line correct and if so should I use it?
| Both lines are in fact correct but do subtly different things.
The first line creates a new object on the stack by calling a constructor of the format Thing(const char*).
The second one is a bit more complex. It essentially does the following
Create an object of type Thing using the constructor Thing(const char*)... |
2,722,939 | 16,694,704 | C++ resize a docked Qt QDockWidget programmatically? | I've just started working on a new C++/Qt project. It's going to be an MDI-based IDE with docked widgets for things like the file tree, object browser, compiler output, etc. One thing is bugging me so far though: I can't figure out how to programmatically make a QDockWidget smaller. For example, this snippet creates my... | I just went through this same process. After trying far too many permutations of resize(), adjustSize() and friends on dock widgets and their contained widget, none of which worked, I ended up subclassing QListView and adding that sizeHint() method.
Now it works like a charm.
|
2,723,146 | 2,723,180 | Create object of unknown class (two inherited classes) | I've got the following classes:
class A {
void commonFunction() = 0;
}
class Aa: public A {
//Some stuff...
}
class Ab: public A {
//Some stuff...
}
Depending on user input I want to create an object of either Aa or Ab. My imidiate thought was this:
A object;
if (/*Test*/) {
Aa object;
} else {
A... | Use a pointer:
A *object;
if (/*Test*/) {
object = new Aa();
} else {
object = new Ab();
}
|
2,723,284 | 2,723,334 | How to detect if the Windows DWORD_PTR type is supported, using an ifdef? | There are some new integer types in the Windows API to support Win64. They haven't always been supported; e.g. they aren't present in MSVC6.
How can I write an #if condition to detect if these types are supported by <windows.h>?
(My code needs to compile under many different versions of Microsoft Visual C++, including... | The macro MSC_VER is a value that is within the range [1200, 1300) for MSVC 6. So you can use #if MSC_VER>=1200 && MSC_VER<1300.
EDIT: As Anders said, this is not really that valid of a test beyond "is my compiler MSVC 6". However, you can also use:
#if defined(MAXULONG_PTR)
Since DWORD_PTR is a value type, it has a m... |
2,723,285 | 2,723,314 | C++ methods which take templated classes as argument | I have a templated class
Vector<class T, int N>
Where T is the type of the components (double for example) and n the number of components (so N=3 for a 3D vector)
Now I want to write a method like
double findStepsize(Vector<double,2> v)
{..}
I want to do this also for three and higher dimensional vectors. Of course ... | Yes it is
template<typename T, int N>
double findStepsize(Vector<T,N> v)
{..}
If you call it with a specific Vector<T, N>, the compiler will deduce T and N to the appropriate values.
Vector<int, 2> v;
// ... fill ...
findStepsize(v); /* works */
The above value-parameter matches your example, but it's better to pass... |
2,723,505 | 2,723,530 | Starting a C++ project. Should I worry about freeing dynamic allocated memory? | I am pretty proficient with C, and freeing memory in C is a must.
However, I'm starting my first C++ project, and I've heard some things about how you don't need to free memory, by using shared pointers and other things.
Where should I read about this? Is this a valuable replacement for proper delete C++ functionality?... |
Where should I read about this?
Herb Sutter's Exceptional C++ and Scott Meyers's More Effective C++ are both excellent books that cover the subject in detail.
There is also a lot of discussion on the web (Google or StackOverflow searches for "RAII" or "smart pointer" will no doubt yield many good results).
Is this... |
2,723,671 | 2,724,034 | How to debug packet loss? | I wrote a C++ application (running on Linux) that serves an RTP stream of about 400 kbps. To most destinations this works fine, but some destinations expericence packet loss. The problematic destinations seem to have a slower connection in common, but it should be plenty fast enough for the stream I'm sending.
Since th... | Don't send out packets in big bursty chunks.
The packet loss is usually caused by slow routers with limited packet buffer sizes. The slow router might be able to handle 1 Mbps just fine if it has time to send out say, 10 packets before receiving another 10, but if the 100 Mbps sender side sends it a big chunk of 50 pa... |
2,723,686 | 2,723,830 | C++ memcpy return value | According to http://en.cppreference.com/w/cpp/string/byte/memcpy C++'s memcpy takes three parameters: destination, source and size/bytes. It also returns a pointer.
void* memcpy( void* dest, const void* src, std::size_t count );
Why is that so? Aren't the parameters enough to input and copy data?
Am I misunderstandin... | If a function has nothing specific to return, it is often customary to return one of the input parameters (the one that is seen as the primary one). Doing this allows you to use "chained" function calls in expressions. For example, you can do
char buffer[1024];
strcat(strcpy(buffer, "Hello"), " World");
specifically b... |
2,723,697 | 2,723,792 | C++ Pointer to a function which takes an instance of a templated class as argument | I have trouble compiling a class, which has function pointers as member variables. The pointers are to functions which take an instance of a class as argument.
Like
template<class T, int N>
double (*f)(Vector<T,N> v);
I get "error: data member 'f' cannot be a member template" Compiler is gcc 4.2.
Edit
Before using tem... | Use a member typedef:
template <typename T, int N>
class Vector
{
public:
/// type of function pointer
typedef double (*FuncPtr)( const Vector& );
};
// concrete type
typedef Vector<double,10> VecDouble10;
// actual function
double func( const VecDouble10>& );
// usage
VecDouble10::FuncPtr fp = func;
|
2,724,110 | 2,724,193 | Can't link Hello World! | Guys that is code copied from a book (Programming Windows 5th edition):
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0) ;
return 0 ;
}
Link to the ... | It will depend on how you set up the project. In VS2010, if I create a new project via File->New->Project, Visual C++, Empty Project, then add a new C++ file, and copy your code in, it compiles and runs just fine.
If you've created a different type of project, it may be using different link libraries. Try right-click... |
2,724,170 | 2,730,073 | OpenGL texture randomly not shown | I have got a very, very strange problem in my C++ OpenGL application.
I simply load a texture and apply it to a quadric:
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,... | Found :) It was the GLint texture member that wasn't correctly reallocated in the copy constructor.
However, i still don't understand why it worked sometimes...
|
2,724,197 | 2,724,213 | Is this not downcasting? | If I do
double d = 34.56;
int i = (int)d;
Am I not "downcasting"?
OR
Is this term only used in terms of classes and objects?
I am confused because in this case we are "downcasting" from a bigger double to a smaller int, but in case of classes, we "downcast" from a smaller base class to a bigger derived class.
Aren't... | No, you are not down casting. You are just casting, and you're chopping off anything after the decimal.
Down casting doesn't apply here. The primitives int and double are not objects in C++ and are not related to each other in the way two objects in a class hierarchy are. They are separate and primitive entities.
Do... |
2,724,242 | 2,724,476 | Multi color Edit Field (Win32) | I want to create a program that will parse text for key words and make these words a certain color. What type of control supports many different colors? Would I have to create my own, or override the OnPaint() of a basic control or something? (Id like to avoid making my own control from scratch)
Thanks
| One option would be to use the rich edit control:
http://www.codeproject.com/KB/edit/RichEditLog_Demo.aspx
Another option would be to build a custom control:
http://www.codeproject.com/KB/edit/brainchild.aspx
|
2,724,252 | 2,728,312 | Qt 4.x: how to implement drag-and-drop onto the desktop or into a folder? | I've written a little file-transfer application written in C++ using Qt 4.x ... it logs into a server, shows the user a list of files available on the server, and lets the user upload or download files.
This all works fine; you can even drag a file in from the desktop (or from an open folder), and when you drop the fil... | Look at QMimeData and its documentation, it has a virtual function
virtual QVariant retrieveData ( const QString & mimetype, QVariant::Type type ) const
this means to do you drag to the outside you implement this functions accordingly
class DeferredMimeData : public QMimeData
{
DeferredMimeData(QString downloadFil... |
2,724,316 | 2,724,465 | C++: Efficiently adding integers to strings | I know how to add integers to strings, but I'm not sure I'm doing it in an efficient matters. I have a class where I often have to return a string plus an integer (a different integer each time), in Java I would do something like
public class MyClass {
final static String S = "MYSTRING";
private int id = 0;
publ... | std::ostringstream is the "standard" way to do this in C++. You might be able to make something more efficient via some custom coding, or laboriously comparing the performance of ostringstream, itoa, and sprintf on all the systems where you'll be deploying this program, but it's probably not worth the effort.
I'd say ... |
2,724,343 | 2,724,515 | Reading File in C++ throwing Seg Fault | When trying to read tokens from a file in C++, I receive a seg fault. Just to play with some things, I tried reading over the file and just printing and surprisingly if you uncomment the code for the first file read and then read the second file everything works fine. If you leave the commented code commented, you rece... | The common process for reading files:
myfile1.open("2a");
// Note the change in the next line
if (!myfile1)
{
cout << "unable to open file1" << endl;
return(0);
}
counter = 0;
// Note, this line differs between the two examples.
myfile1 >> m;
file1_minutiaes = new Minutiae[m];
// Note the change in the foll... |
2,724,359 | 2,724,668 | Are there any modern platforms with non-IEEE C/C++ float formats? | I am writing a video game, Humm and Strumm, which requires a network component in its game engine. I can deal with differences in endianness easily, but I have hit a wall in attempting to deal with possible float memory formats. I know that modern computers have all a standard integer format, but I have heard that th... | I think it is safe to assume that each platform has an implementation of the IEEE-754 spec that you can rely on. However, even if they all implement the same spec, there is no guarantee that each platform has the exact same implementation, has the same FP control flags set, does the same optimizations, or implements th... |
2,724,366 | 2,727,053 | protecting COM interfaces from exceptions | I have several dozen objects exposed through COM interfaces, each of which with many methods, totaling a few hundred methods. These interfaces expose business objects from my app to a scripting engine.
I have been given the task of protecting every single one of these methods from exceptions being thrown (to catch the... | The most reliable C++ way is to use macros here. I' ready to accept downvotes for saying this, but we've been using this solution for years and haven't seen any serious problems so far.
Define a "begin method" macro for clearing IErrorInfo and try { and "end method" for } catch and the error handling. If you design the... |
2,724,402 | 2,724,413 | Is there any standard delete functor? | I am looking for a functor that deletes its argument:
template<class T>
struct delete_functor
{
void operator()(T* p)
{
delete p;
}
};
Is there something like this in std, tr1 or boost?
| C++0x will add std::default_delete to the standard library to support std::unique_ptr.
It has effectively the same functionality as your delete_functor, but is also specialized to call delete[] for array type objects.
|
2,724,530 | 2,724,559 | Opt-out of copy constructor | This might be a silly question, but...
I've been writing a number of classes that utilize non-copyable members. These classes are never initialized via the copy constructor in my source. When I try to compile without supplying my own copy-constructor, g++ throws out many errors about how it can't build a default copy... | If you don't actually cause the copy-constructor to be called then it is not an error if the compiler would be unable to generate one. It sounds like you are (possibly indirectly) causing the copy-constructor to be used.
You can suppress the compiler generated one by declaring your own copy-constructor (you don't need ... |
2,724,579 | 2,724,596 | Can I cause a new C++ class instance to fail if certain conditions in the constructor are not met? | As I understand it, when a new class is instantiated in C++, a pointer to the new class is returned, or NULL, if there is insufficient memory. I am writing a class that initializes a linked list in the constructor. If there is an error while initializing the list, I would like the class instantiator to return NULL.
F... | The common approach here is to throw an exception (and handle it somewhere higher up).
One of the benefits of the exception mechanism is that it allows you to throw an exception from within a class constructor. In that case, you never reach the situation where a pointer is returned to the invalid. You would "get contro... |
2,724,651 | 2,724,688 | Drawing continuously in drawing application | I was wondering how drawing applications draw the entire time the mouse is down without having empty gaps. What I mean is, for example if the program only drew circles at the mouse's X, y coordinate, then if the mouse went too quicly it would seem like a bunch of little circles rather than a nice continuous line. How c... | It can't be done without constantly drawing a line between the current mouse point and the previous point, which is why this is what drawing programs generally do do.
Fancier drawing programs will fit curvy lines to multiple previous points to achieve a more natural drawing stroke, but the principle is the same.
Update... |
2,724,708 | 2,724,815 | Is it a good practice to pass struct object as parameter to a function in c++? | I tried an example live below:
typedef struct point
{
int x;
int y;
} point;
void cp(point p)
{
cout<<p.x<<endl;
cout<<p.y<<endl;
}
int main()
{
point p1;
p1.x=1;
p1.y=2;
cp(p1);
}
The result thats printed out is:
1
2
which is what I expected. My question is: Does parameter p get the... | There is nothing wrong with passing structs as parameters. Everything is passed by value in C++ so a full copy is indeed made.
The struct you gave in your example is small so it's probably not a problem if you pass it by value. But if you work with bigger data structures, you may want to pass it by reference.
Beware th... |
2,724,722 | 2,724,782 | C++ new memory allocation fragmentation | I was trying to look at the behavior of the new allocator and why it doesn't place data contiguously.
My code:
struct ci {
char c;
int i;
}
template <typename T>
void memTest()
{
T * pLast = new T();
for(int i = 0; i < 20; ++i) {
T * pNew = new T();
cout << (pNew - pLast) << " ";
... | There are two issues:
most allocators store some additional data prior to the start of the block (typically block size and a couple of pointers)
there are usually alignment requirements - modern operating systems typically allocate to at least an 8 byte boundary.
So you'll nearly always get some kind of gap between s... |
2,725,044 | 2,725,129 | Can I assume (bool)true == (int)1 for any C++ compiler? | Can I assume (bool)true == (int)1 for any C++ compiler ?
| According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.
The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which q... |
2,725,123 | 2,725,127 | Is there a way to make C macros keyword agnostic? | Is there a way to concatenate keywords in a macro and get
C to behave in a more dynamic fashion as in:
#define macro(fun,ction,var,iable) function(variable)
I know this kind of thing exists in other languages.
| You can use ## to concatinate names in macros
fun##ction ...
|
2,725,285 | 2,725,486 | When should I use temporary variables? | Specifically, I'm wondering which of these I should write:
{
shared_ptr<GuiContextMenu> subMenu = items[j].subMenu.lock();
if (subMenu)
subMenu->setVisible(false);
}
or:
{
if (items[j].subMenu.lock())
items[j].subMenu.lock()->setVisible(false);
}
I am not required to follow any style guide... | An alternative method:
if(shared_ptr<GuiContextMenu> subMenu = items[j].subMenu.lock()) {
subMenu->setVisible(false);
}
//subMenu is no longer in scope
I'm assuming subMenu is a weak_ptr, in which case your second method creates two temporaries, which might or might not be an issue. And your first method adds a v... |
2,725,348 | 2,725,468 | How can a class's memory-allocated address be determined from within the constructor? | Is it possible to get the memory-allocated address of a newly-instantiated class from within that class's constructor?
I am developing a linked list where multiple classes have multiple pointers to like classes. Each time a new class instantiates, it needs to check its parent's list to make sure it is included.
If I t... | Did you mean to do:
pParents->rels[i] = this;
|
2,725,369 | 2,725,628 | Problem with GetDefaultPrinter() over a VPN c++ | I am writing an application that gets its dimensions from the paper ratio of the default printer of the local computer. This all works well unless the default printer is over a VPN. When this is the case, calling GetDefaultPrinter() takes too long. I need to find a way to put a time constraint on GetDefaultPrinter() an... | Would putting this sort of functionality into a separate thread be acceptable?
|
2,725,674 | 2,725,696 | Can my loop be optimized any more? | Below is my innermost loop that's run several thousand times, with input sizes of 20 - 1000 or more. This piece of code takes up 99 - 99.5% of execution time. Is there anything I can do to help squeeze any more performance out of this?
I'm not looking to move this code to something like using tree codes (Barnes-Hut), ... |
Inline the calls to lengthsq().
Change pow(r2,-1.5) to 1/(r2*sqrt(r2)) to lower the cost of the computing r^1.5
Use scalars (p_i_acc, etc.) inside the innner most loop rather than p[i].acc to collect your result. The compiler may not know that p[i] isn't aliased with p[j], and that might force addressing of p[i] on ... |
2,725,737 | 2,725,745 | Lock-Free Data Structures in C++ Compare and Swap Routine | In this paper: Lock-Free Data Structures (pdf) the following "Compare and Swap" fundamental is shown:
template <class T>
bool CAS(T* addr, T exp, T val)
{
if (*addr == exp)
{
*addr = val;
return true;
}
return false;
}
And then says
The entire procedure is atomic
But how is that so? Is it not possib... | He is describing an atomic operation which is given by the implementation, "somehow." That is pseudo-code for something implemented in hardware.
|
2,725,802 | 2,726,327 | C++ arrays as parameters, EDIT: now includes variable scoping | Alright, I'm guessing this is an easy question, so I'll take the knocks, but I'm not finding what I need on google or SO. I'd like to create an array in one place, and populate it inside a different function.
I define a function:
void someFunction(double results[])
{
for (int i = 0; i<100; ++i)
{
for (i... | Just a point about the variable scope part of the question - there is no issue of variable scope here. result/results in your someFunction definition is a parameter -> it will take on the value passed in. There is no relation between variables in a called function and it's caller -> the variables in the caller function... |
2,725,803 | 2,725,826 | What does '#if _LFS64_LARGEFILE-0' mean to CPP? | What does #if _LFS64_LARGEFILE-0 mean to the C Preprocessor for g++? Is that a minus zero or is that part of the symbol? If it is minus zero, how does that affect whether the #if is triggered?
| That is a more robust version of:
#if _LFS64_LARGEFILE
i.e. that the code should be conditionally included if _LFS64_LARGEFILE has a true value.
Adding the - 0, prevents you from getting a warning (#if with no expression) when _LFS64_LARGEFILE is not defined.
|
2,725,815 | 2,726,175 | Link Error : xxx is already defined in *****.LIB :: What exactly is wrong? | Problem:
I'm trying to use a library named DCMTK which used some other external libraries ( zlib, libtiff, libpng, libxml2, libiconv ). I've downloaded these external libraries (*.LIB & *.h files ) from the same website. Now, when I compile the DCMTK library I'm getting link errors (793 errors) like this:
Error 2 e... |
Whats up with the "Debug Mode"
(Multi-Threaded Debug) and "Release
Mode" (Multi-Threaded)? What exactly
is happening under the hood? Why
exactly this thing is causing linking
error?
The linker drags in libraries for several different reasons. The simplest is that a library is listed on the linker command l... |
2,725,823 | 2,725,853 | How do i get the screen to pause? |
Possible Duplicate:
How to stop C++ console application from exiting immediately?
So im learning c++ and i was given this example and i wanted to run it. But i cannot get it to stay up, unless i change it. How do i get Microsoft visual 2010 to keep up the screen when it gets to the end of the program after I release... | In Visual C++ you can either:
Put a breakpoint at the closing brace of main and run attached to the debugger (Debug -> Start Debugging). When the breakpoint is hit you will be able to view the console window.
Run detached from the debugger (Debug -> Start Without Debugging). When the application terminates, the cons... |
2,726,012 | 2,726,064 | Dynamic 2d array in c++ and memory leaks | I wrote this code. It runs OK, but when I check it under Valgrind it catches 2 problems. Since I can not interpret valgrind's messages i will appreciate if anyone explain me more and tell me where is the problem!!!
Here is the code:
#include <iostream>
#define width 70000
#define height 10000
using namespace std;
... | Okay, there are a couple of Valgrind warnings I get with 3.4 but only the first is important.
new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. Sorry.
new throws an exception when it is out of memory (unless you use the nothrow version of new). Unfortun... |
2,726,079 | 2,726,121 | C++ Beginner Delete code | I am attempting to dynamically allocate memory to the heap and then delete the allocated memory. Below is the code that is giving me a hard time:
// String.cpp
#include "String.h"
String::String() {}
String::String(char* source)
{
this->Size = this->GetSize(source);
this->CharArray = new char[this->Size + 1];
int ... | Change your default ctor; given the error you're getting, the delete call is trying to delete a pointer that has never been initialized.
String::String() : Size(0), CharArray(NULL) {}
Also, beware of the "copy constructor". You might want to make it private just to be sure you're not triggering it implicitly. (It do... |
2,726,130 | 2,732,789 | Double Linked List Insertion Sorting Bug | I have implemented an insertion sort in a double link list (highest to lowest) from a file of 10,000 ints, and output to file in reverse order.
To my knowledge I have implemented such a program, however I noticed in the ouput file, a single number is out of place. Every other number is in correct order.
The number ou... | I don't like this part
else
{
while(temp->next!=NULL && temp!=this->back)
{
if(temp->value >= inValue)
{
insertBefore(inValue, temp);
return;
}
temp = temp->next;
}
}
if(temp == this->back)
{
insertBack(inValue);
}
Imagine what happens if ... |
2,726,146 | 2,726,155 | Convert "this" to a reference-to-pointer | Let's say I have a struct
struct Foo {
void bar () {
do_baz(this);
}
/* See edit below
void do_baz(Foo*& pFoo) {
pFoo->p_sub_foo = new Foo; // for example
}
*/
Foo* p_sub_foo;
}
GCC tells me that
temp.cpp: In member function ‘void Foo::bar()’:
temp.cpp:3: error: no matching f... | You can't.
Firstly, this is not necessarily a const Foo *. this would be a const Foo * is a const method of the class Foo. In a non-const method this is just Foo *. (Actually your error message mentions Foo* const. Where did you see const Foo *?)
Secondly, and more importantly, this is not an lvalue. You can't have a ... |
2,726,176 | 2,726,351 | Can I get the amount of time for which a key is pressed on a keyboard | I am working on a project in which I have to develop bio-passwords based on user's keystroke style.
Suppose a user types a password for 20 times, his keystrokes are recorded, like
holdtime : time for which a particular key is pressed.
digraph time : time it takes to press a different key.
suppose a user types a pass... | You mentioned you'd prefer it in C, but since you tagged it Python... :)
Also, since you say you're looking for building a dataset, I assume you'll have to invite users to type in arbitrary text, so you'll need some sort of interface (graphical or otherwise).
Here's a quick example using pygame. You can trivially modif... |
2,726,204 | 2,726,221 | C++ preprocessor #define-ing a keyword. Is it standards conforming? | Help settle the debate that's going on in the comments at this question about bool and 1:
Can a standards-conforming C++ preprocessor allow one to use #define to redefine a language keyword? If so, must a standards-conforming C++ preprocessor allow this?
If a C++ program redefines a language keyword, can that program i... | In C++, the closest thing to forbidding #defineing a keyword is §17.4.3.1.1/2, which only disallows it in a translation unit that includes a standard library header:
A translation unit that includes a header shall not contain any macros that define names declared or defined in that header. Nor shall such a translatio... |
2,726,340 | 2,726,347 | Unresolved external symbol error in c++ | I am trying to do a simple hw problem involving namespace, static data members and functions. I am getting an unresolved external symbol error
Error 1 error LNK2001: unresolved external symbol "private: static double JWong::SavingsAccount::annualInterestRate" (?annualInterestRate@SavingsAccount@JWong@@0NA) Sav... | I'm presuming you are actually compiling the .cpp file (because the other functions link).
The error is likely due to not defining the annualInterestRate static variable.
You have declared it (in the class header), but it's not defined. In your cpp file add:
// static member definition
double JWang::SavingsAccount::an... |
2,726,356 | 2,726,363 | the "new" operator in c++, pointer question | Dumb question, but whenever you call new, do you always have a pointer?
SomeClass *person = new SomeClass();
And is that because you need a pointer to point to that new space of memory that was allocated for the SomeClass variable person? Thanks!
| If new completes successfully, it always returns a pointer (if it doesn't complete successfully, an exception is thrown, and nothing is returned).
The pointer is to the object that was created, or in the case of an array, a pointer to the first element of the array.
|
2,726,370 | 2,726,374 | how to make a name from random numbers? | my program makes a random name that could have a-z this code makes a 16 char name but
:( my code wont make the name and idk why :( can anyone show me what's wrong with this?
char name[16];
void make_random_name()
{
byte loop = -1;
for(;;)
{
loop++;
srand((unsigned)time(0));
int random_integ... | random_integer is an integer, you are comparing it to a bunch of characters from the ASCII character set - '1' as a character literal is actually 49 in decimal. As 49 is not in the range of your random numbers, it'll never get hit.
Try changing your case statements to
case 1: ...
instead of
case '1': ...
|
2,726,408 | 2,726,534 | What is the proper way to declare a specialization of a template for another template type? | The usual definition for a specialization of a template function is something like this:
class Foo {
[...]
};
namespace std {
template<>
void swap(Foo& left, Foo& right) {
[...]
}
} // namespace std
But how do you properly define the specialization when the type it's specialized on is itself a... | Your solution isn't a template specialization, but an overload of a function in the std namespace, which is "undefined behavior" per the c++ standard.
This question is exactly your question.
Scott Meyers discusses this in Effective C++, and there is a followup thread on usenet's comp.lang.c++.
He suggests that you def... |
2,726,413 | 2,726,453 | C++ Translation Phase Confusion | Can someone explain why the following doesn't work?
int main() // Tried on several recent C++ '03 compilers.
{
#define FOO L
const wchar_t* const foo = FOO"bar"; // Will error out with something like: "identifier 'L' is undefined."
#undef FOO
}
I thought that preprocessing was done in an earlier translation phas... | Use:
#define FOO L\
without the trailing \ there will be a space between L and the string on macro substitution. This is from the result of g++ -E :
const wchar_t* const foo = L "bar";
|
2,726,422 | 2,733,538 | using declarations in main (C++) | Although you wouldn't want to do this, if you have a namespace COMPANY, and a class in that namespace SOMECLASS. Why is it that in the .cpp file, you might define the functions as
COMPANY::SOMECLASS::someFunction()
{}
But in main, I get errors for doing:
int main() {
COMPANY::SOMECLASS::someFunction();
}
but inste... | The problem is simply in your declaration in main - you're accessing constructor, not the type, and you can't really reference the constructor directly.
Change main to:
int main()
{
JWong::SavingsAccount *saver1 = new JWong::SavingsAccount(2000.00);
}
...and you should be good to go.
|
2,726,560 | 2,727,027 | Creating a Transparent Bitmap with GDI? | I want to implement a layering system in my application and was thinking of creating a bunch of transparent bitmaps, adding content to them then blitting them on top of each other, how can this be done without setting each pixel to (0,0,0,0). I'm using Pure win32, not MFC, thanks.
| What do you mean by transparent?
If you are looking for partial (to full) transparency, then AlphaBlend is the GDI API to use. Loading bitmaps with alpha is tricky - The only format the base windows API supports for loading bitmaps with alpha is a 32bpp .BMP file with an alpha channel in the top 8 bits of each byte - a... |
2,726,960 | 2,726,968 | C++ "delayed" template argument | Is there direct way to do the following:
template < class >
struct f {};
template < class F >
void function() {
F<int>(); //for example
// ? F template <int>();
}
function < f >();
I have workaround by using extra class around template struct.
I am wondering if it's possible to do so directly.
Thanks
| The proper syntax for template template-parameters is as follows
template < class > struct f {};
template < template <class> class F >
void function() {
F<int>(); //for example
}
...
function < f >()
|
2,726,993 | 2,727,033 | How to specify preference of library path? | I'm compiling a c++ program using g++ and ld. I have a .so library I want to be used during linking. However, a library of the same name exists in /usr/local/lib, and ld is choosing that library over the one I'm directly specifying. How can I fix this?
For the examples below, my library file is /my/dir/libfoo.so.0. Thi... | Add the path to where your new library is to LD_LIBRARY_PATH (it has slightly different name on Mac ...)
Your solution should work with using the -L/my/dir -lfoo options, at runtime use LD_LIBRARY_PATH to point to the location of your library.
Careful with using LD_LIBRARY_PATH - in short (from link):
..implications..... |
2,727,031 | 2,727,130 | Makefile can not find boost libraries installed by macports | I just installed boost 1.42.0 from macports using sudo port install boost.
Everything worked fine. Now I have a project that I'm trying to build using a makefile. Everything builds fine until it comes to the file that needs the boost library.
It says:
src/graph.h:20:42: error: boost/graph/adjacency_list.hpp: No suc... | You need to tell the compiler the base directory where Boost is intalled. You can do that with the compiler's -I command line option:
g++ -I/opt/local/include ...
|
2,727,139 | 2,727,281 | format, iomanip, c++ | I'm trying to learn to use namespaces declarations more definitive than not just say "using namespace std". I'm trying to format my data to 2 decimal places, and set the format to be fixed and not scientific. This is my main file:
#include <iostream>
#include <iomanip>
#include "SavingsAccount.h"
using std::cout;
us... | You want std::fixed (the other one just inserts its value into the stream, which is why you see 8192), and I don't see a call to std::setprecision in your code anywhere.
This'll fix it:
#include <iostream>
#include <iomanip>
using std::cout;
using std::setprecision;
using std::fixed;
int main()
{
cout << fixed <<... |
2,727,228 | 2,729,091 | Load a Lua script into a table named after filename | I load scripts using luaL_loadfile and then lua_pcall from my game, and was wondering if instead of loading them into the global table, I could load them into a table named after their filename?
For example:
I have I file called "Foo.lua", which contains this:
function DoSomething()
--something
end
After loading i... | Try something like this. Don't forget to add error checking...
lua_newtable(L);
lua_setglobal(L,filename);
luaL_loadfile(L,filename);
lua_getglobal(L,filename);
lua_setfenv(L,-2);
lua_pcall(L,...);
|
2,727,287 | 2,727,344 | Why is floating point byte swapping different from integer byte swapping? | I have a binary file of doubles that I need to load using C++. However, my problem is that it was written in big-endian format but the fstream >> operator will then read the number wrong because my machine is little-endian. It seems like a simple problem to resolve for integers, but for doubles and floats the solutions... | The most portable way is to serialize in textual format so that you don't have byte order issues. This is how operator>> works so you shouldn't be having any endian issues with >>. The principal problem with binary formats (which would explain endian problems) is that floating point numbers consist of a number of manti... |
2,727,293 | 2,727,307 | fftw in Visual Studio? | I'm trying to link my project with fftw and so far, I've gotten it to compile, but not link. As the site said, I generated all the .lib files (even though I'm only using double precision), and copied them to C:\Program Files\Microsoft Visual Studio 9.0\VC\lib, the .h file to C:\Program Files\Microsoft Visual Studio 9.0... | Have you actually linked against the library in the project you're building?
Project -> Properties -> Linker -> Input -> Additional dependencies
You need to add the library's filename to that field.
|
2,727,402 | 2,727,428 | Difference of function argument as (const int &) and (int & a) in C++ | I know that if you write void function_name(int& a), then function will not do local copy of your variable passed as argument. Also have met in literature that you should write void function_name(const int & a) in order to say compiler, that I dont want the variable passed as argument to be copied.
So my question: what... | You should use const in the signature whenever you do not need to write. Adding const to the signature has two effects: it tells the compiler that you want it to check and guarantee that you do not change that argument inside your function. The second effect is that enables external code to use your function passing ob... |
2,727,582 | 2,727,653 | multiple definition in header file | Given this code sample:
complex.h :
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
class Complex
{
public:
Complex(float Real, float Imaginary);
float real() const { return m_Real; };
private:
friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx);
float m_Real;
float m_Imagi... | The problem is that the following piece of code is a definition, not a declaration:
std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
You can either mark the function above and make it "inline" so that multiple translation units may define it:
i... |
2,727,803 | 2,731,329 | Cannot insert a breakpoint in shared Library | Friends
While debugging an application of of the function is defined in a shared library which is written by another vendor .
and I get an error like
warning: Cannot insert breakpoint 0: in /opt/trims/uat/lib/libTIPS_Oleca.sl
warning: This is because your shared libraries are not mapped private. To attach to a proces... | You don't need to modify the shared library.
Instead, you must modify your main executable (by running pxdb -s or chatr +dbg enable on it).
The a.out in the message you are getting refers to your main executable -- it's a UNIX convention that the output from linker is called a.out if you don't explicitly name it.
|
2,727,834 | 2,727,872 | C++ standard: dereferencing NULL pointer to get a reference? | I'm wondering about what the C++ standard says about code like this:
int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;
In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard?
Under different circumstances a dereferencing of a NULL ... | Dereferencing a NULL pointer is undefined behavior.
In fact the standard calls this exact situation out in a note (8.3.2/4 "References"):
Note: in particular, a null reference cannot exist in a well-defined program, because the only
way to create such a reference would be to bind it to the “object” obtained by der... |
2,727,860 | 2,727,904 | From Java/C++ to XML | I know Java and C++ but am looking to get in to XML. I don't want to waste time reading over the basics of programming in a book, so has anyone any recommendations for resources for learning XML that assume a knowledge of programming already, or even better highlight how to switch from Java/C++ to XML ie. main differen... | XML is not a programming language. It is a markup language. It's mainly used to store/transmit data in a structured manner.
If you know Java and C++, there are libraries out there that can load and parse XML files.
Adding to Soto's answer, you can technically use it to describe behavior (e.g. XAML, processing instructi... |
2,727,890 | 2,727,902 | C++ struct sorting error | I am trying to sort a vector of custom struct in C++
struct Book{
public:int H,W,V,i;
};
with a simple functor
class CompareHeight
{
public:
int operator() (Book lhs,Book rhs)
{
return lhs.H-rhs.H;
}
};
when trying :
vector<Book> books(X);
.....
sort(books.begin(),books.end(), CompareHeight());
... | sort expects a function that returns bool, which is true iff the lhs precedes the rhs:
bool operator() (const Book& lhs, const Book& rhs)
{
return lhs.H < rhs.H;
}
Also note the change to const Book& parameters, to avoid copying.
|
2,728,078 | 2,728,235 | Is there an easy way to check a fundamental type | In < Modern C++ Design >,it introduces a way to check if a type fundamental type by introducing the so called type list. but what if I don't want to include so many loki code and just want a simple function to implement that? What is the simplest way to do that?
| You can use template specialization to get what you want.
// General template
template<typename T>
struct IsFundamentalType { enum { result = false }; };
// Template specializations for each fundamental type
template<>
struct IsFundamentalType<char> { enum { result = true }; };
template<>
struct IsFundamentalType<int... |
2,728,190 | 2,728,318 | How are iterators and pointers related? | Code with iterators looks pretty much like code with pointers. Iterators are of some obscure type (like std::vector<int>::iterator for example).
What I don't get is how iterators and pointer are related to each other - is an iterator a wrapper around a pointer with overloaded operations to advance to adjacent elements ... | Iterators are a generalization of pointers.
An iterator (depending on the variants) have to implement * and ++
So a pointer IS an iterator. But not necessarily the other way round.
If you want to iterate over a complex structure (a tree, a graph...), the iterator will be much more than a pointer, and doesn't make any r... |
2,728,239 | 2,728,305 | C++ delete[] operator | Is this the right way to use delete[] operator?
int* a=new int[size];
delete[] a;
If yes, Who (compiler or GC or whoever) will determine the size of the newly created array? and where will it store the array size?
Thanks
| For each chunk of memory allocated, the memory allocator stores the size of the chunk (that's why it is inefficient to allocate many small blocks compared to one big one for example). When delete frees the memory, the allocator knows how large the memory chunk is the pointer points to.
|
2,728,255 | 2,728,322 | C++: getting the address of the start of an std::vector? | Sometimes it is useful to use the starting address of an std::vector and temporarily treat that address as the address of a regularly allocated buffer.
For instance replace this:
char* buf = new char[size];
fillTheBuffer(buf, size);
useTheBuffer(buf, size);
delete[] buf;
With This:
vector<char> buf(size);
fillTh... | I guess you'd just have to check.
Perhaps a utility function:
template <class T, class Alloc>
T* data(std::vector<T, Alloc>& vec)
{
return vec.empty() ? 0 : &vec[0];
}
template <class T, class Alloc>
const T* data(const std::vector<T, Alloc>& vec)
{
return vec.empty() ? 0 : &vec[0];
}
|
2,728,299 | 2,728,427 | Why is comparing against "end()" iterator legal? | According to C++ standard (3.7.3.2/4) using (not only dereferencing, but also copying, casting, whatever else) an invalid pointer is undefined behavior (in case of doubt also see this question). Now the typical code to traverse an STL containter looks like this:
std::vector<int> toTraverse;
//populate the vector
for( s... | You're right that an invalid pointer can't be used, but you're wrong that a pointer to an element one past the last element in an array is an invalid pointer - it's valid.
The C standard, section 6.5.6.8 says that it's well defined and valid:
...if the expression P points to the
last element of an array object, the
... |
2,728,518 | 2,728,548 | class foo; in header file | Is some one able to explain why header files have something like this?
class foo; // This here?
class bar
{
bar();
};
Do you need an include statement when using this?
Thanks.
| The first class foo; is called a forward declaration of the class foo. It simply lets the compiler know that it exists and that it names a class. This makes foo what is called an "incomplete type" (unless the full declaration of foo has already been seen). With an incomplete type, you can declare pointers of that type,... |
2,728,576 | 2,728,723 | what is the difference between Template Explicit Specialization and ordinary function? | template <class T>
void max (T &a ,T &b)
{}//generic template #1
template<> void max(char &c, char &d)
{} //template specializtion #2
void max (char &c, char &d)
{}//ordinary function #3
what is difference between 1 ,2, and 3?
|
is a template function
is a total specialization of the previous template function (doesn't overload!)
is an overload of the function
Here is an excerpt from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices:
66) Don't specialize function templates
Function template specializations never participate in... |
2,728,658 | 2,794,749 | Are there any Visual Studio add-ins for true 'smart tabs'? | 'Smart Tabs' concept allows to automatically insert tab character for block indentation and space characters for in-block formatting. It's described here. Unfortunately, Visual Studio's 'smart tabs' option in text editor settings just indents text on enter press. Same name, completely different and near useless thing :... | If no one comes up with an "as-you-type" utility, then Astyle with its convert-tabs and indent=tab options will reformat code after-the-fact.
|
2,728,880 | 2,733,665 | Modifying an image with OpenGL? | I have a device to acquire XRay images. Due to some technical constrains, the detector is made of heterogeneous pixel size and multiple tilted and partially overlapping tiles. The image is thus distorted. The detector geometry is known precisely.
I need a function converting these distorted images into a flat image wit... | You might find this tutorial useful (it's a bit old, but note that it does contain some OpenGL 2.x GLSL after the Cg section). I don't believe there are any shortcuts to image processing in GLSL, if that's what you're looking for... you do need to understand a lot of the 3D rasterization aspect and historical baggage ... |
2,728,944 | 2,728,954 | On C++ global operator new: why it can be replaced | I wrote a small program in VS2005 to test whether C++ global operator new can be overloaded. It can.
#include "stdafx.h"
#include "iostream"
#include "iomanip"
#include "string"
#include "new"
using namespace std;
class C {
public:
C() { cout<<"CTOR"<<endl; }
};
void * operator new(size_t size)
{
co... | Yes, global operator new is special in that programs may provide a replacement implementation for it.
Replaceable forms are the single object and array forms of operator new and operator delete and the "no throw" variants. Other forms, such as placement new are not replaceable.
|
2,728,951 | 2,736,704 | Simple menubar using Qt4 | i'm trying to make a simple GUI with QT 4.6. i made a separete class that represents the menu bar:
MenuBar::MenuBar()
{
aboutAct = new QAction(tr("&About QT"), this);
aboutAct->setStatusTip(tr("Show the application's About box"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
quitAct = n... | You have a typo. :)
In: connect(quitAct, SIGNAL(triggered()), &QApp, SLOT(quit()));
The variable's name is qApp, not QApp. That aside, balpha said it all. So it's either:
connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
or
connect(quitAct, SIGNAL(triggered()), QApplication::instance(), SLOT(quit()));
|
2,729,202 | 2,729,360 | Aborted core dumped C++ | I have a large C++ function which uses OpenCV library and running on Windows with cygwin g++ compiler. At the end it gives Aborted(core dumped) but the function runs completely before that. I have also tried to put the print statement in the end of the function. That also gets printed. So I think there is no logical bu... | It looks like a memory fault (write to freed memory, double-free, stack overflow,...). When the code can be compiled and run under Linux you can use valgrind to see if there are memory issues. Also you can try to disable parts of the application until the problem disappears, to get a clue where the error happens. But t... |
2,729,280 | 2,729,403 | Adding a string or char array to a byte vector | I'm currently working on a class to create and read out packets send through the network, so far I have it working with 16bit and 8bit integers (Well unsigned but still).
Now the problem is I've tried numerous ways of copying it over but somehow the _buffer got mangled, it segfaulted, or the result was wrong.
I'd appre... | Since you're using an std::vector for your buffer, you may as well let it keep track of the write position itself and avoid having to keep manually resizing it. You can also avoid writing multiple overloads of the add function by using a function template:
template <class T>
Packet& add(T value) {
std::copy((uint8_... |
2,729,371 | 2,729,485 | Creating multiple MFC dialogs through COM, strange behaviour | Updated: please see this other thread instead, all this COM stuff is not part of the problem.
One of our apps has a COM interface which will launch a dialog, e.g:
STDMETHODIMP CSomeClass::LaunchDialog(BSTR TextToDisplay)
{
CDialog *pDlg = new CSomeDialog(TextToDisplay);
pDlg->BringWindowToTop();
}
For some reason... | It sounds like the first dialog has been set as the owner of the second, and the second as the owner of the third. Can you change the dialog initialization to explicitly specify the owner window? Is there a window that makes sense to assign? Perhaps the Desktop window, if they're all intended to be top-level?
If you... |
2,729,372 | 2,729,597 | QMetaMethods for regular methods missing? | I'm new in QT, and I'm just testing out the MOC.
For a given class:
class Counter : public QObject
{
Q_OBJECT
int m_value;
public:
Counter() {m_value = 0;}
~Counter() {}
int value() {return m_value;}
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
};
I want to get a list of al... | As far as I remember you can't access all methods of a QObject subclass through the QMetaObject it provides access only for the signals, slots and INVOCABLE methods:
class MyClass: public QObject {
Q_OBJECT
public:
Q_INVOCABLE int someMethod(const QString &someParam);
};
Maybe it's also provide access ... |
2,729,417 | 2,729,474 | C++: How to count all instantiated objects at runtime? | I have a large framework consisting of many C++ classes. Is there a way using any tools at runtime, to trace all the C++ objects that are being constructed and currently exist?
For example, at a certain time t1, perhaps the application has objects A1, A2 and B3, but at time t2, it has A1, A4, C2 and so on?
This is a c... | You can inject code in the destructor and constructor of the objects that you want to count:
SomeObject::SomeObject() {
++globalSomeObjectCounter;
}
SomeObject::~SomeObject() {
--globalSomeObjectCounter;
}
Don't forget to increase the counter in all constructors (copy constructors, etc.)
EDIT: In this situation... |
2,729,512 | 2,729,563 | Calls to singleton library | I have a singleton class, and I will compile it as a library static(lib) or dynamic(dll).
Is it guaranteed that calls to same file in a machine always refer to same and unique instance in both cases?
Edit:
What if a process loads two different library and different functions from these libraries want to use instance of... | No, different processes will not share a singleton from a common library. Different processes use different memory spaces, so each will instantiate its own singleton.
You'll need to use some sort of shared memory or interprocess-communication to share data between processes.
If a single process loads libraries A and B... |
2,729,829 | 2,729,893 | Any way to profile code for cache behavior? | As the title says I'd like to somehow get the cache behavior of my code. I'm running Windows 7 64-bit edition, compiling on Visual Studio 2008 Professional Edition, compiling C++ code.
I understand that there's Valgrind under Linux, but are there any free alternatives I could use, or methods otherwise?
| VTune will give you pretty detailed cache and pipeline analysis. It's not cheap though. I believe some level/edition of VS (I remember it was "team edition" on XP) had a decent profiler.
|
2,730,000 | 2,730,116 | Serializing struct containing char* | I'm getting an error with serializing a char* string error C2228: left of '.serialize' must have class/struct/union I could use a std::string and then get a const char* from it. but I require the char* string.
| The error message says it all, there's no support in boost serialization to serialize pointers to primitive types.
You can do something like this in the store code:
int len = strlen(string) + 1;
ar & len;
ar & boost::serialization::make_binary_object(string, len);
and in the load code:
int len;
ar & len;
string = new ... |
2,730,105 | 2,730,857 | C++ Static Initializer - Is it thread safe | Usually, when I try to initialize a static variable
class Test2 {
public:
static vector<string> stringList;
private:
static bool __init;
static bool init() {
stringList.push_back("string1");
stringList.push_back("string2");
stringList.push_back("string3");
return true;
}... | I asked a similar question a while back:
LoadLibrary and Static Globals
When it comes to DLLs, static initialization and the call to DllMain is bracketed by an internal critical section, so they are thread-safe. A second thread will wait until the first is done before it loads the DLL.
So in short, your static init is ... |
2,730,110 | 2,731,671 | Why typedef char CHAR | Guys, having quick look in Winnt.h I have discovered that there is a lots of typedefs and one of them is for example CHAR for a char. Why? What was the purpose of these typdefs? Why not use what's already there (char, int etc.)?
Thank you.
| The WIN32 API needs to be platform agnostic as well. When the compiler adjusts for different word sizes, the types may also change as well.
For example, on 16-Bit platforms:
typedef WORD unsigned int;
typedef DWORD unsigned long;
On 32-bit platforms:
typedef WORD unsigned short;
typedef DWORD unsigned int;
This ... |
2,730,117 | 2,730,132 | C++ - Efficient container for large amounts of searchable data? | I am implementing a text-based version of Scrabble for a College project.
My dictionary is quite large, weighing in at around 400.000 words (std::string).
Searching for a valid word will suck, big time, in terms of efficiency if I go for a vector<string> ( O(n) ). Are there any good alternatives? Keep in mind, I'm enro... | If you wanted to go for something that is in the standard library, you could use std::set with the word as the key. That would give you logarithmic search time.
Since your dictionary is presumably static (i.e. created once and not modified), you could also use a std::vector, sort it using std::sort, and then use std... |
2,730,604 | 2,730,666 | How do I build boost examples with bjam? | Boost library is full of examples and tests and I would like to build them using bjam if possible.
How do I build boost examples with bjam?
PS. I wasn't able to locate proper documentation for this option.
| It depends on the library. Most of them run the examples from the test directory. Others from the example directory.
Go to the lib test or example directory where there is a Jamfile and do just
bjam
|
2,730,663 | 2,730,767 | How (if needed) to free dynamic memory when marshaling CString from C++ to C#? | I have CString cs on C++ side and IntPtr ip on C# side which contains value of cs through marshaling mechanism.
Then, I simply get needed String as Marshal.PtrToStringAnsi(ip) and everything works fine, but I am wondering should I and if should, how can I delete unmanaged memory occupied by ip, i.e. cs?
| You can't, you have no idea what allocator was used by the unmanaged code to create the CString instance. Moreover, you'd have to call the CString destructor, you can't get its address.
You are dead in the water if this CString object is returned as the function return value of a C++ function that you call from C#. I... |
2,730,817 | 2,730,860 | How to extract ALL typedefs and structs and unions from c++ source | I have inherited a Visual Studio project that contains hundreds of files.
I would like to extract all the typedefs, structs and unions from each .h/.cpp file and put the results in a file).
Each typdef/struct/union should be on one line in the results file. This would make sorting much easier.
typdef int myType;
str... | I can't imagine a purpose for this except for some sort of documentation effort. If that is what you're looking for I would suggest doxygen.
To answer your question, I seriously doubt any amount of regular expressions will be sufficient. What you need to do is actually parse the code. I have heard of a library out t... |
2,730,963 | 2,752,445 | Complex error handling | I've got a particularly ornery piece of network code. I'm using asio but that really doesn't matter for this question. I assume there is no way to unbind a socket other than closing it. The problem is that open(), bind(), and listen() can all throw a system_error. So I handled the code with a simple try/catch. The... | I would suggest just doing separate error handling for open, since there is different cleanup before and after:
bool connect()
{
try {
m_acceptor.open( m_address.protocol() );
} catch( const boost::system::system_error& error ) {
return false;
}
try {
m_acceptor.set_option( tcp::acceptor::reuse_... |
2,731,016 | 2,731,259 | Detect if an assembly is available | I'm implementing an installer in Java, that is supposed to download and install an application for non-privileged users in Windows (from XP and up). The application is written in C++, and depend on the usual VC runtime-libraries (msvcm90.dll and friends). In order to save bandwidth, I want to avoid downloading the VC ... | If you are willing to write a small test program, then rather than writing one that looks for your dependencies, write one that has the same dependencies as your application. Try to run it. If it runs, the dependencies are in place. If it fails, the probable reason is that the dependencies are missing.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.