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,319,772 | 2,319,836 | What is the preference of function/method/template name resolving in C++? | How does the C++ compiler decide which function/method to call if there are multiple possibilities?
In my specific case I have the standard free function of the C++ Run time and I also have a templated free variant, like this:
// The definitions of the C++ Run Time Library (from memory.h)
extern malloc(size_t s);
extern void free(void *p);
// Our own memory management functions
extern void *OurMalloc(size_t s);
extern void OurFree(void *p);
// Own variants to overrule malloc and free (instead of using #define)
template<typename T>
void *malloc(T t)
{
return OurMalloc(t);
}
template<typename T>
void free(T *t)
{
OurFree(t);
}
I tested this using the following code:
void main(void)
{
void *p = malloc(10);
free(p);
}
If I compile and run this, it seems that the call to malloc is correctly replaced by the templated variant. So far, so good.
However, the call to free is not replaced by the templated variant, and the standard C++ function is still called.
What rules does the C++ compiler use to decide which variant to give priority?
Is this related to the Koenig-lookup rules?
Note: I tried this alternative because using #define does not solve the problem (see question How to use C macro's (#define) to alter calls but not prototypes).
| Overload resolution is quite complicated in general.
In your case, it is quite easy: a function template is not considered if there is an exact match. For free it is the case (the standard free takes a void*), for malloc it isn't (the standard malloc takes a size_t, you are passing an int and size_t can't be a typedef for int -- size_t is unsigned). If you call free with a type other than void*, it should instantiate your template.
Running:
#include <iostream>
void* ml(size_t s)
{
std::cout << "ml(size_t)\n";
}
void fr(void *p)
{
std::cout << "fr(void*)\n";
}
template<typename T>
void* ml(T t)
{
std::cout << "ml<" << typeid(T).name() << ">(T)\n";
}
template<typename T>
void fr(T *t)
{
std::cout << "fr<" << typeid(T).name() << ">(T*)\n";
}
int main()
{
void* p1 = ml((size_t)10);
fr(p1);
int* p2 = (int*)ml(10);
fr(p2);
return 0;
}
I get
ml(size_t)
fr(void*)
ml<i>(T)
fr<i>(T*)
and i is what returns typeid(int).name()
|
2,319,924 | 2,319,962 | What is process and thread? | Yes, I have read many materials related to operating system. And I am still reading. But it seems all of them are describing the process and thread in a "abstract" way, which makes a lot of high level elabration on their behavior and logic orgnization. I am wondering what are they physically? In my opinion, they are just some in-memory "data structures" which are maintained and used by the kernel codes to facilitate the execution of program. For example, operating system use some process data structure (PCB) to describe the aspects of the process assigned for a certain program, such as its priority, its address space and so on. Is this all right?
| Normally when you run an executable like notepad.exe, this creates a single process. These process could spawn other processes, but in most cases there is a single process for each executable that you run. Within the process, there can be many threads. Usually at first there is one thread, which usually starts at the programs "entry point" which is the main function usually. Instructions are executed one by one in order, like a person who only has one hand, a thread can only do one thing at a time before it moves on to the next.
That first thread can create additional threads. Each additional thread has it's own entry point, which is usually defined with a function. The process is like a container for all the threads that have been spawned within it.
That is a pretty simplistic explanation. I could go into more detail but probably would overlap with what you will find in your textbooks.
EDIT: You'll notice there are lot's of "usually"'s in my explanation, as there are occasionally rare programs that do things drastically different.
|
2,319,927 | 2,320,055 | How can I define a "Do-Nothing" sort? | I'm working on a system where I need to be able to sort a vector by a given predicate, which my classes shouldn't have control over. Basically, I pass them a derived class and they blindly sort on it.
As one of the "delightful quirks", one of the sort patterns is order of entry.
Here's what I've got so far.
struct Strategy
{
virtual bool operator()(const Loan& lhs, const Loan& rhs) const = 0;
};
struct strategyA : public Strategy
{
bool operator()(const Loan& lhs, const Loan& rhs) const
{
return true;
}
};
struct strategyB : public Strategy
{
bool operator()(const Loan& lhs, const Loan& rhs) const
{
return lhs.getID() > rhs.getID();
}
};
struct strategyC : public Strategy
{
bool operator()(const Loan& lhs, const Loan& rhs) const
{
return lhs.getFee() > rhs.getFee();
}
};
Obviously, as strategyA is reflexive, it can't be used, and if I set it to false, it'll treat everything as equal and I can kiss my data goodbye.
So here's my question. Is there a way of defining a predicate function for sorting a vector which will NOT change anything?
I'm aware that possibly the simplest solution is to add an order of entry variable to the Loan class, or partner it with one in a pair. Alternatively I could feed a parameter in with the predicate that tells the sorter whether to use it or not.
| Personally, I think your strategy class should have a "sort" method. That way, it can either call std::sort or not, as it sees fit. Whether as well as how becomes part of the sorting strategy.
Darios stable_sort answer is very good, if you can use it.
It is possible to do sorting based on item position in a vector, but it doesn't mean items won't move (many sort algorithms will basically scramble-then-resort your data), so you have to have some reliable way of determining where the items were when you started.
It's possible for the comparison to keep a mapping of current-position to original-position, but a lot of work. Ideally the logic needs to be built into the sort algorithm - not just the comparison - and that's essentially how stable_sort works.
Another problem - depending on the container - the order of (say) item addresses isn't always the order of the items.
|
2,320,105 | 2,320,120 | Tracking down the origin of a VS2k8 error message? | I have several maps containing a multitude of classes in my VC++ project, some of them default constructable, others not. When trying to build, I get a "no appropriate default constructor available" error. The problem is that the error is listed to occur in line 173 of map.cpp, which is the code for operator[]. It would seem that I'm accidentally calling operator[] (which implicitly calls the mapped type's default constructor) on one of my non-default constructable maps, but VS doesn't give me any info on where the error originated.
How can I find the part in my code that's causing this problem?
| You're probably looking inside the error list window. Which I don't use that often for C++ projects.
Go to the output window and check a little further down, you should be able to double click the line that will bring you to the type in question.
Doing a search for : error inside the output window is very common for me as well as : fatal to find the source of the errors. Also if you have C++ keyboard shortcuts setup you can keep hitting F4 to go down the list of errors.
To reset to the default C++ keyboard mappings:
Options -> Environment -> Keyboard
Then reset keyboard mappings to: Visual C++ 6.
|
2,320,426 | 2,320,450 | Errors while compiling a test program using Qt | I am pretty new to C++/Qt
I am following the book 'C++ GUI Programming with Qt 4' by Jasmin Blanchette and Mark Summerfield.
I was working on an example program and got stuck up with some compilation errors which I was not able to resolve. Code and Errors below. Any help is appreciated.
Thanks.
finddialog.h
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton;
class QWidget;
class FindDialog : QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = 0);
signals:
void findNext(const QString &str, Qt::CaseSensitivity cs);
void findPrevious(const QString &str, Qt::CaseSensitivity cs);
private slots:
void findClicked();
void enableFindButton(const QString &text);
private:
QLabel *label;
QLineEdit *lineEdit;
QCheckBox *caseCheckBox;
QCheckBox *backwardCheckBox;
QPushButton *findButton;
QPushButton *closeButton;
};
#endif // FINDDIALOG_H
finddialog.cpp
#include <QtGui>
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent) : QDialog(parent)
{
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);
caseCheckBox = new QCheckBox(tr("Match &case"));
backwardCheckBox = new QCheckBox(tr("Search &backward"));
findButton = new QPushButton(tr("&Find"));
findButton->setDefault(true);
findButton->setEnabled(false);
closeButton = new QPushButton(tr("Close"));
connect(lineEdit, SIGNAL(textChanged(QString)), this, SLOT(enableFindButton(QString)));
connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked()));
connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
QHBoxLayout *topLeftLayout = new QHBoxLayout;
topLeftLayout->addWidget(label);
topLeftLayout->addWidget(lineEdit);
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout(topLeftLayout);
leftLayout->addWidget(caseCheckBox);
leftLayout->addWidget(backwardCheckBox);
QVBoxLayout *rightLayout = new QVBoxLayout;
rightLayout->addWidget(findButton);
rightLayout->addWidget(closeButton);
rightLayout->addStretch();
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
setLayout(mainLayout);
setWindowTitle(tr("Find"));
setFixedHeight(sizeHint().height());
}
void FindDialog::findClicked()
{
QString text = lineEdit->text();
Qt::CaseSensitivity cs =
caseCheckBox->isChecked() ? Qt::CaseSensitive
: Qt::CaseInsensitive;
if (backwardCheckBox->isChecked()) {
emit findPrevious(text, cs);
} else {
emit findNext(text, cs);
}
}
void FindDialog::enableFindButton(const QString &text)
{
findButton->setEnabled(!text.isEmpty());
}
main.cpp
#include <QApplication>
#include "finddialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
FindDialog *dialog = new FindDialog;
dialog->show();
return app.exec();
}
Errors below..
c:/Qt/2010.02.1/qt/include/QtGui/../../src/gui/kernel/qwidget.h:
In function 'int qMain(int, char**)':
c:/Qt/2010.02.1/qt/include/QtGui/../../src/gui/kernel/qwidget.h:485:
error: 'void QWidget::show()' is
inaccessible main.cpp:7: error: within
this context main.cpp:7: error:
'QWidget' is not an accessible base of
'FindDialog'
| You should inherit publically from QWidget or QDialog:
class FindDialog : public QDialog {
// ...
show() is actually implemented by a base of FindDialog, QWidget - but you are not inheriting publically from it and thus can't access it.
Inheritance for classes is by default private, i.e.
class A : B {};
and
class A : private B {};
are equivalent.
|
2,320,433 | 2,320,605 | Why is my DCOM client locking on a call to SendMessage? | Running on XP. I have a client that calls calls CoInitializeEx(NULL, COINIT_MULTITHREADED), loads a (local) DCOM object, and attaches an event interface so the DCOM object can send back events. The client looks a lot like notepad with a multi-line textbox covering the client area to display event messages. Here are the calls that create a lock-up:
Client calls p->DoStuff() on the DCOM object.
The DCOM object calls c->DoStuffEvent() on the client while processing DoStuff().
The client sends a EM_REPLACESEL message to the child textbox to have it display "stuff is happening"
The client freezes on the SendMessage(EM_REPLACESEL). The client's call to p->DoStuff() is done on a the main thread while the SendMessage(EM_REPLACESEL) is done on a different thread. I'm sure this has something to do with the problem.
Can someone explain what's causing the lock and how I might work around it? The client and DCOM objects are coded by me in MSVC/ATL, so I can modify them both as needed.
| It would appear that the window was created by the main thread. So that is the only thread that can call the window proc. When you SendMessage from the other thread, what it actually does it to put the message into the main thread's queue and then wait for the main thread to call GetMessage or PeekMessage. Inside the call to GetMessage or PeekMessage, Windows notices a waiting cross-thread SendMessage and passes that message to the window proc, then it wakes the second thread and lets it continue.
If you don't care about the return value of SendMessage(EM_REPLACESEL), you can use SendNotifyMessage instead. But if you do this, you need to make sure that the string you pass with the EM_REPLACESEL message is still valid when the message is finally delivered.
|
2,320,595 | 2,320,726 | Finding the spread of each cluster from Kmeans | I'm trying to detect how well an input vector fits a given cluster centre. I can find the best match quite easily (the centre with the minimum euclidean distance to the input vector is the best), however, I now need to work how good a match that is.
To do this I need to find the spread (standard deviation?) of the vectors which build up the centroid, then see if the distance from my input vector to the centre is less than the spread. If it's more than the spread than I should be able to say that I have no clusters to fit it (given that the best doesn't fit the input vector well).
I'm not sure how to find the spread per cluster. I have all the centre vectors, and all the training vectors are labelled with their closest cluster, I just can't quite fathom exactly what I need to do to get the spread.
I hope that's clear? If not I'll try to reword it!
TIA
Ian
| Use the distance function and calculate the distance from your center point to each labeled point, then figure out the mean of those distances. That should give you the standard deviation.
|
2,320,665 | 2,320,758 | What are custom calling conventions? | What are these? And how am I affected by these as a developer?
Related:
What are the different calling conventions in C/C++ and what do each mean?
| A calling convention describes how something may call another function. This requires parameters and state to be passed to the other function, so that it can execute and return control correctly. The way in which this is done has to be standardized and specified, so that the compiler knows how to order parameters for consumption by the remote function that's being called. There are several standard calling conventions, but the most common are fastcall, stdcall, and cdecl.
Usually, the term custom calling convention is a bit of a misnomer and refers to one of two things:
A non-standard calling convention or one that isn't in widespread use (e.g. if you're building an architecture from scratch).
A special optimization that a compiler/linker can perform that uses a one-shot calling convention for the purpose of improving performance.
In the latter case, this causes some values that would otherwise be pushed onto the stack to be stored in registers instead. The compiler will try to make this decision based on how the parameters are being used inside the code. For example, if the parameter is going to be used as a maximum value for a loop index, such that the index is compared against the max on each iteration to see if things should continue, that would be a good case for moving it into a register.
If the optimization is carried out, this typically reduces code size and improves performance.
And how am I affected by these as a developer?
From your standpoint as a developer, you probably don't care; this is an optimization that will happen automatically.
|
2,320,846 | 2,320,912 | Find if QTreeWidgetItem is top level | Is there a way I can find out if the QTreeWidgetItem I'm looking at is top level or not? I have a program crashing when I try to take the text of a parent if the item is top level (no parent).
| Quoting the documentation:
The main difference between top-level
items and those in lower levels of the
tree is that a top-level item has no
parent(). This information can be used
to tell the difference between items,
and is useful to know when inserting
and removing items from the tree.
if (!node.parent()) {
// top-level item
}
|
2,320,847 | 2,320,876 | Class design suggestions: extending a class and code reuse | The gist of this question is about extending a class, minimizing jam-packing everything into a single class, and maximizing code re-use. After reading this question, please feel free to edit the title or description to make it more succinct. Though the post looks long, I am just trying to be thorough by using a lot of examples.
Suppose I have a class:
class UsedByManyPeople
{
// ...has many fields
};
As the name implies, this class is used by a lot of developers. I have to add 2 features to this class:
a convert() that converts UsedByManyPeople to SomeOtherType
a getFileName() that returns a string
Both of them are specific to my department's needs.
First attempt solution
At first I thought about simply adding 2 new methods to UsedByManyPeople.Thus, the class will now look like:
class UsedByManyPeople
{
// ...has many fields
public:
SomeOtherType const convert() const;
std::string const getFileName() const;
};
However, the 2 features are actually specific to my department's use case, and other departments do not even have the class definition of SomeOtherType nor do they care about the getFileName().
Clearly, the above approach is not a good approach (?).
How would you extend this class?
Alternatives that came to my mind:
Subclass UsedByManyPeople and create my own class.
Tie data and method together
For example,
class ExtUsedByManyPeople : public UsedByManyPeople
{
public:
SomeOtherType const convert() const;
std::string const getFileName() const;
};
Create Helper classes, one for each method (yikes!), and implement it as static methods.
Separate data from methods, single class one responsibility
For example,
class UsedByManyPeopleToSomeOtherTypeConverter
{
public:
static SomeOtherType const convert(UsedByManyPeople const&);
};
class UsedByManyPeopleFileName
{
public:
static std::string const getFileName(UsedByManyPeople const&);
};
Create a single Helper class, with all the methods inside.
Separate data from methods, single class many responsibilities
For example,
class UsedByManyPeopleHelper
{
public:
static SomeOtherType const convert(UsedByManyPeople const&);
static std::string const getFileName(UsedByManyPeople const&);
};
| Especially if the methods are specific to your departments use of the class you should implement them as in: Create a single Helper class, with all the methods inside.
There are several reasons for this:
The single helper class can be
located in another logical project
structure
If your new methods don't require access to the internal state of the class this is expressed clearly. It provides better encapsulation. (which you supplemented by const ref, which is think is a good style)
UsedByManyPeople shouldn't
be responsible for converting itself
into another type. This violates
SOLID
|
2,320,901 | 2,321,005 | Design Question: How can I maintain a stack of object | I have a struct call 'A', which has an attribute 'i', like this:
typedef struct a {
a() { i = 0;}
int i;
} A;
And I would like to maintain a stack of A in my Main class:
class Main {
public:
void save();
void doSomethingToModifyCurrentA();
void restore();
private:
A currentA;
stack<A> aStack;
}
I would like to write the function save() which save the current values of A (e.g. i) to the stack and I can go on doSomethingToModifyCurrentA() to change currentA. And then later on, I can restort A by calling restore().
My question are
How can I allocate memory for a copy of A to the 'stack'?
How can I pop out the copy of A and free the memory and restore the value of 'currentA'?
| You don't need to do anything to reserve memory on the stack. The underlying container (deque by default) manages memory for you.
The three important methods are...
mystack.push (myvalue);
mystack.top ();
mystack.pop ();
The pop doesn't read the top value - just discards it. The top method returns a reference to the current top value, so you can write...
??? = mystack.top ();
mystack.top () = ???;
To read or overwrite the top value.
These methods translate to the following calls in the underlying deque...
mydeque.push_back (myvalue);
mydeque.back ();
mydeque.pop_back ();
Personally, I usually just use the deque directly - though strictly, the stack is better for readability and maintainability as it better expresses the intent and prevents you from doing some things incompatible with that intent.
|
2,321,070 | 2,321,222 | replace _asm nop in 64-bit, VS2008, C++ | How to replace _asm nop instructions in 64-bit. compiles and works in 32-bit.
| I believe that you can use the __nop intrinsic function. This should compile into the appropriate machine instruction for the processor that you are building.
http://msdn.microsoft.com/en-us/library/aa983381(VS.80).aspx
UPDATE:
Here is an example that I just created with VS2008. It compiles for both Win32 and x64 configurations:
#include "stdafx.h"
#include <intrin.h>
int _tmain(int argc, _TCHAR* argv[])
{
// The intrinsic function below will compile to a NOP machine instruction.
// This is the same as _asm nop in the 32-bit compiler.
__nop();
return 0;
}
In case you are wondering, I disassembled the above example and the x64 output was:
wmain proc near
db 66h
nop
nop
xor eax, eax
retn
wmain endp
The Win32 output was:
_main proc near
nop
xor eax, eax
retn
_main endp
|
2,321,305 | 2,327,178 | Only include certain items in CComboBox type ahead? | I have a dropdown-list style CComboBox on a form. The nice thing about this style is it allows for type ahead--that is, you can type a character and it will jump to the first item in the list matching that character. However, there are certain items which need to be excluded from this behavior. How might this be accomplished?
| Just as a simple (and maybe ugly) "trick" idea: Can you mask the items you want to exclude from type ahead search by any special character, like * as first character for instance? (So you would add to the ComboBox *MyItemText instead of MyItemText.) If your item list needs to be sorted you have to switch off the autosort property of the ComboBox and do your own sorting (without the *) before you add the items to the ComboBox. Users would also recognize that this is an item not to be found by type ahead (if this makes any sense or should be useful in your application).
The CComboBox does not have any Edit or TextChanged event. So my guess is that for another better solution you have to go the hard way and evaluate single keyboard events and run own your search through the item list. I don't have a better idea.
|
2,321,515 | 2,321,832 | Using expat to parse xml | I need to get attributes name and values of an xml file with many elements.
what is the best way to capture the attribute values in a class?
I have to following code for the startelement handler:
start(void *data, const char *el, const char **attr)
{
int i;
// Skip the ParameterList element
if(strcmp(el, "ParameterList") == 0)
{
Depth++;
return;
}
//for (i = 0; i < Depth; i++)
//printf(" ");
//printf("%s", el);
DEMData demData;
for (i = 0; attr[i]; i += 2)
{
if(strcmp(attr[i],"BitFldPos") == 0)
{
demData.SetBitFldPos(*attr[i + 1] - '0');
}
else if(strcmp(attr[i],"BytFldPos") == 0)
{
char* pEnd;
int tmp = strtol(attr[i + 1],&pEnd,10);
demData.SetBytFldPos(tmp);
}
else if(strcmp(attr[i],"ByteOrder") == 0)
{
demData.SetByteOrder(attr[i + 1]);
}
else if(strcmp(attr[i],"DesS") == 0)
{
demData.SetDesS(attr[i + 1]);
}
else if(strcmp(attr[i],"EngUnit") == 0)
{
demData.SetEngUnit(attr[i + 1]);
}
else if(strcmp(attr[i],"OTag") == 0)
{
demData.SetOTag(attr[i + 1]);
}
else if(strcmp(attr[i],"ValTyp") == 0)
{
demData.SetValType(attr[i + 1]);
}
else if(strcmp(attr[i],"idx") == 0)
{
char* pEnd;
int tmp = strtol(attr[i + 1],&pEnd,10);
demData.SetIndex(tmp);
}
//printf(" %s='%s'", attr[i], attr[i + 1]);
}
// Insert the data in the vector.
dems.push_back(demData);
Depth++;
}
| I would recommend an STL vector of STL pairs of strings. first is the attribute name, second is the value.
std::vector<std::pair<std::string,std::string> >
Some would suggest an std::map.
|
2,321,578 | 2,321,596 | C++: why can't we have references to references or array of references? | I noticed that there is no reference to reference but there is pointer to pointer, and also there is no an array of references but an array of pointers.
Could anybody give me any reason?
| Pointers are mutable (if non-const), references never. Thus there is no point having a pointer or reference to a reference.
Also, a reference must always refer to something - there is no such thing as a null reference. This is why there can be no arrays of references, as there is no way to default instantiate references inside an array to a meaningful value.
|
2,321,663 | 2,321,725 | Why do I get warning C4081 on this #pragma? | I am in the habit of removing all warning reported in my code. I just like a clean build if possible. I used
#pragma comment(lib,"some.lib");
I get this warning:
warning c4081: expected 'newline'; found ';'
I am uncertain why that would create a warning. Could I get help on removing it?
| Its the semi-colon at the end of the line. Its not needed for #pragma.
edit: The warning says it all: Expected a newline at the end of the pragma, but found a semi-colon instead.
Tested with VS2008
|
2,321,713 | 2,321,731 | How do I avoid name collision with macros defined in Windows header files? | I have some C++ code that includes a method called CreateDirectory(). Previously the code only used STL and Boost, but I recently had to include <windows.h> so I could look-up CSIDL_LOCAL_APPDATA.
Now, this code:
filesystem.CreateDirectory(p->Pathname()); // Actually create it...
No longer compiles:
error C2039: 'CreateDirectoryA' : is not a member of ...
Which corresponds to this macro in winbase.h:
#ifdef UNICODE
#define CreateDirectory CreateDirectoryW
#else
#define CreateDirectory CreateDirectoryA
#endif // !UNICODE
The pre-processor is redefining my method call. Is there any possible way to avoid this naming collision? Or do I have to rename my CreateDirectory() method?
| You will be better off if you just rename your CreateDirectory method. If you need to use windows APIs, fighting with Windows.h is a losing battle.
Incidently, if you were consistent in including windows.h, this will still be compiling. (although you might have problems in other places).
|
2,321,790 | 2,322,056 | How do I layout my C++ program? (where should I put the .h and .cpp files?) | Currently, I program in Java and use Maven quite a bit. As so I've become accustom to the naming schemes and folder structures that I've used over the past 4 or 5 years.
As I have recently started to learn C++, I'm realizing that I have no idea where to put all my files. Should I keep everything broken down by namespace, or by what tier it is in? Where, for example, would I keep a series of files devoted to UI, as apposed to files meant to help store data?
Are there any standards for this sort of thing?
Clearly, there is no definitive answer to this question. I'm simply looking for a good guide. I do not want to start learning C++ by spending too much time worrying about how my files are laid out. I'd rather have some good models, and just get to the coding.
| The following is fairly typical...
third-party library
release
obj
debug
obj
include
src
sublib 1
sublib 2
mylibrary
release
obj
debug
obj
include
src
sublib 1
sublib 2
myapp
release
obj
debug
obj
subapp 1
subapp 2
mylittleapp
release
obj
debug
obj
Basically, subfolders for subprojects is common for larger projects, but mostly a particular project has folders for src, include etc. A folder for each build configuration is common, and keeping the obj files and other intermediates in a subfolder of that is a good idea. It may be tempting to put subproject folders in obj folders, but usually that's unnecessary - the obj folders don't need to be well organised, so the only concern is a filename conflict, and the best fix for that is to have unique source filenames within (at least) each project.
The "include" folders should IMO only contain headers that will be #included by other projects - internal headers belong in the "src" folder.
Putting UI stuff in a separate folder isn't a bad idea, if it's big enough. I've seen UI stuff done as a separate static-linked top-level project, and I do mean app-specific here, not (e.g.) wxWidgets. Usually, though, that level of division is sub-project if it's worth separating at all. How you divide subprojects is more a matter of application-specific blocks in general, so it depends on whether UI stuff is best handled as a separate block or as separate chunks mixed in with task-specific logic.
Namespaces aren't the most used language feature, possibly because a lot of people use "using" so much they don't make much difference. A namespace for a main library project makes sense, but associating subfolders to namespaces 1:1 isn't something I've seen. I personally have a namespace that encompasses most of my library code, with a couple of sub-namespaces for things rarely used in general, but used a lot in a few places (e.g. a "bitwise" namespaces). The sub-namespaces are limited to single source/header pairs, so no need for subfolders. Most of the library-specific selection is done by including the right header - except that I usually include the lot through a main-project top-level header anyway.
Basically, namespaces are a way of avoiding naming conflicts. They don't necessarily associate with abstractions or functional blocks or anything. Within a particular project, you're probably better off just making sure the names don't conflict. As with the "std" namespace, it's fine to put a lot of stuff in one namespace.
As you say, though, this isn't a definitive answer - there are of course minor variations and quite different approaches.
|
2,321,908 | 2,321,986 | Issue with using std::copy | I am getting warning when using the std copy function.
I have a byte array that I declare.
byte *tstArray = new byte[length];
Then I have a couple other byte arrays that are declared and initialized with some hex values that i would like to use depending on some initial user input.
I have a series of if statements that I use to basically parse out the original input, and based on some string, I choose which byte array to use and in doing so copy the results to the original tstArray.
For example:
if(substr1 == "15")
{
std::cout<<"Using byte array rated 15"<<std::endl;
std::copy(ratedArray15,ratedArray15+length,tstArray);
}
The warning i get is
warning C4996: 'std::copy': Function call with parameters
that may be unsafe
- this call relies on the caller to check that the passed
values are correct.
A possible solution is to to disable this warning is by useing -D_SCL_SECURE_NO_WARNINGS, I think. Well, that is what I am researching.
But, I am not sure if this means that my code is really unsafe and I actually needed to do some checking?
| C4996 means you're using a function that was marked as __declspec(deprecated). Probably using D_SCL_SECURE_NO_WARNINGS will just #ifdef out the deprecation. You could go read the header file to know for sure.
But the question is why is it deprecated? MSDN doesn't seem to say anything about it on the std::copy() page, but I may be looking at the wrong one. Typically this was done for all "unsafe string manipulation functions" during the great security push of XPSP2. Since you aren't passing the length of your destination buffer to std::copy, if you try to write too much data to it it will happily write past the end of the buffer.
To say whether or not your usage is unsafe would require us to review your entire code. Usually there is a safer version they recommend when they deprecate a function in this manner. You could just copy the strings in some other way. This article seems to go in depth. They seem to imply you should be using a std::checked_array_iterator instead of a regular OutputIterator.
Something like:
stdext::checked_array_iterator<char *> chkd_test_array(tstArray, length);
std::copy(ratedArray15, ratedArray15+length, chkd_test_array);
(If I understand your code right.)
|
2,321,924 | 2,322,107 | Forward declaration of 'const struct list::SingleList' , Invalid use of incomplete type 'list::SingleList' (Compilation errors) | SingleList.h
#include "ListBase.h"
#include "DataNode.h"
#include "SingleListIterator.h"
namespace list
{
class SingleListIterator;
class SingleList : public ListBase
{
private:
DataNode *head;
DataNode *tail;
public:
SingleList();
SingleList(const SingleList &obj);
~SingleList();
void Flush(); //deletes all elements in the list
void PushInFront(const int data); // **
void Append(const int data); // **
void DeleteLast();
void DeleteFirst();
int Delete(const int& data); // ** remove the first occurrence of data and return 1 otherwise 0
const int& GetFirst() const; // **
int& GetFirst(); // **
const int& GetLast() const; // **
int& GetLast(); // **
void PrintList() const;
const int IsEmpty() const;
// SingleList<T> &operator=(const SingleList<T>& obj) (**)
// const int operator==(const SingleList<T> &obj) const (**)
// const int operator!=(const SingleList<T> &obj) const (**)
// SingleList<T>& operator+(const SingleList<T> &obj) (**) // concatenates two lists
// operator int() // returns list size (**)
friend class SingleListIterator; // ** ASK Changd it from Iterator
};
SingleListIterator.h
#include "Iterator.h"
#include "SingleList.h"
namespace list
{
class SingleList;
class SingleListIterator: public Iterator
{
public:
// error here --> Forward declaration of 'const struct list::SingleList'
SingleListIterator(const SingleList &list); // **
SingleListIterator(const SingleListIterator &obj); // **
virtual const int Current() const; // **
virtual void Succ();
virtual const int Terminate() const;
virtual void rewind();
// T &operator++(int) (**)
// SingleListIterator<T>& operator=(const SingleListIterator<T>&obj) (**)
};
// error here --> Invalid use of incomplete type 'list::SingleList'
SingleListIterator::SingleListIterator(const SingleList &list) : Iterator(list.head)
{
}
Errors indicated in code
Also what can I do in a case like this where there is mutual coupling between two header files ?????
Thaaaaanks
| You use forward declarations, but you anyway include the .h files recursively. The point of the forward declarations is that you don't need to include the headers of the
forward declared class, thereby breaking the mutual dependency.
Also it should be enough to use a forward declaration for one of the classes, not for both of them.
I would suggest the following structure:
SingleListIterator.h:
class SingleList; // forward declaration
class SingleListIterator {
// Declarations, only using pointers/references to SingleList.
// Definitions that need to know the structure of SingleList (like maybe
// a constructor implementation) need to be done in the .cpp file.
};
SingleList.h:
#include "SingleListIterator.h" // include full declaration
class SingleList {
// declarations
};
SingleListIterator.cpp:
#include "SingleListIterator.h"
#include "SingleList.h" // include full declaration of the type
// forward-declared in SingleListIterator.h
// method definitions,...
SingleList.h:
#include "SingleList.h" // include full declarations of everything
// definitions
This way there are no files that mutually include each other and all types are completely known in the implementation (.cpp) files.
|
2,321,972 | 2,322,163 | Argument order for mixed const and non-const pass-by-reference | In keeping with the practice of using non-member functions where possible to improve encapsulation, I've written a number of classes that have declarations which look something like:
void auxiliaryFunction(
const Class& c,
std::vector< double >& out);
Its purpose is to do something with c's public member functions and fill a vector with the output.
You might note that its argument order resembles that of a python member function, def auxiliaryFunction(self, out).
However, there are other reasonable ways of choosing the argument order: one would be to say that this function resembles an assignment operation, out = auxiliaryFunction(c). This idiom is used in, for example,
char* strcpy ( char* destination, const char* source );
What if I have a different function that does not resemble a non-essential member function, i.e. one that initializes a new object I've created:
void initializeMyObject(
const double a,
const std::vector<double>& b,
MyObject& out);
So, for consistency's sake, should I use the same ordering (mutable variable last) as I did in auxiliaryFunction?
In general, is it better to choose (non-const , const) over (const, non-const), or only in certain situations? Are there any reasons for picking one, or should I just choose one and stick with it?
(Incidentally, I'm aware of Google style guide's suggestion of using pointers instead of non-const references, but that is tangential to my question.)
| The STL algorithms places output (non-const) values last. There you have a precedent for C++ that everyone should be aware of.
I also tend to order arguments from important, to less important. (i.e. size of box goes before box-margin tweak value.)
(Note though: Whatever you do, be consistent! That's infinitely more important than choosing this or that way...)
|
2,321,981 | 2,322,082 | Is there a way to know if the user has enabled "single click to open an item" in the control panel? | My program needs to know when the user has enabled "Single-click to open an item (point to select)" in the folder options window in file explorer. I have a mouse aid program and I need to know what this setting is set to programmatically? Is this available in the registry or something?
| I think it's SHGetSettings when fDoubleClickInWebView is false
|
2,322,095 | 2,322,280 | Why does this program crash: passing of std::string between DLLs | I have some trouble figuring out why the following crashes (MSVC9):
//// the following compiles to A.dll with release runtime linked dynamically
//A.h
class A {
__declspec(dllexport) std::string getString();
};
//A.cpp
#include "A.h"
std::string A::getString() {
return "I am a string.";
}
//// the following compiles to main.exe with debug runtime linked dynamically
#include "A.h"
int main() {
A a;
std::string s = a.getString();
return 0;
} // crash on exit
Obviously (?) this is due to the different memory models for the executable and DLL. Could it be that the string A::getString() returns is being allocated in A.dll and freed in main.exe?
If so, why - and what would be a safe way to pass strings between DLLs (or executables, for that matter)? Without using wrappers like shared_ptr with a custom deleter.
| This isn't actually being caused by differing heap implementations - the MSVC std::string implementation doesn't use dynamically allocated memory for strings that small (it uses the small string optimization). The CRTs do need to match, but that isn't what bit you this time.
What's happening is that you're invoking undefined behaviour by violating the One Definition Rule.
The release and debug builds will have different preprocessor flags set, and you'll find that std::string has a different definition in each case. Ask your compiler what sizeof(std::string) is - MSVC10 tells me that it's 32 in a debug build and 28 in a release build (this isn't padding - 28 and 32 are both 4 bytes` boundaries).
So what's happening? Variable s is initialized using the debug version of the copy constructor to copy a release version of std::string. The offsets of the member variables are different between the versions, so you copy garbage. The MSVC implementation effectively stores begin and end pointers - you've copied garbage into them; because they're no longer null, the destructor tries to free them and you get an access violation.
Even if the heap implementations were the same it would crash, as you're freeing garbage pointers to memory that was never allocated in the first place.
In summary: the CRT versions need to match but so do the definitions - including the definitions in the standard library.
|
2,322,255 | 2,326,485 | 64-bit version of Boost for 64-bit windows | Is there a version of 64-bit Boost library for VS2008 ?
Or do I have to compile one myself? if, so, does anyone have experience with it?
| As a short answer:
bjam --toolset=msvc-9.0 address-model=64 --build-type=complete
As a longer answer, here are my build notes for having VS .NET 2008 32-bit and 64-bit boost libraries in the same hierarchy (which is I suspect a common use case):
Build the win32 binaries
bjam --toolset=msvc-9.0 --build-type=complete stage
Create the directory lib\win32
Move the contents of stage\lib to lib\win32
Remove the directories bin.v2 and stage
Build the x64 binaries
bjam --toolset=msvc-9.0 address-model=64 --build-type=complete stage
Create the directory lib\x64
Move the contents of stage\lib to lib\x64
Remove the directories bin.v2 and stage
|
2,322,266 | 2,322,283 | What should I know about multithreading and when to use it, mainly in c++ | I have never come across multithreading but I hear about it everywhere. What should I know about it and when should I use it? I code mainly in c++.
| Mostly, you will need to learn about MT libraries on OS on which your application needs to run. Until and unless C++0x becomes a reality (which is a long way as it looks now), there is no support from the language proper or the standard library for threads. I suggest you take a look at the POSIX standard pthreads library for *nix and Windows threads to get started.
|
2,322,357 | 2,322,598 | C++ ">>" and "<<" IO in C#? | Is there a C# library that provides the functionality of ">>" and "<<" for IO in C++? It was really convenient for console apps. Granted not a lot of console apps are in C#, but some of us use it for them.
I know about Console.Read[Line]|Write[Line] and Streams|FileStream|StreamReader|StreamWriter thats not part of the question.
I dont think im specific enough
int a,b;
cin >> a >> b;
IS AMAZING!!
string input = Console.ReadLine();
string[] data = input.split( ' ' );
a = Convert.ToInt32( data[0] );
b = Convert.ToInt32( data[1] );
... long winded enough? Plus there are other reasons why the C# solution is worse. I must get the entire line or make my own buffer for it. If the line im working on is IDK say the 1000 line of Bells Triangle, I waste so much time reading everything at one time.
EDIT:
GAR!!!
OK THE PROBLEM!!!
Using IntX to do HUGE number like the .net 4.0 BigInteger to produce the bell triangle. If you know the bell triangle it gets freaking huge very very quickly. The whole point of this question is that I need to deal with each number individually. If you read an entire line, you could easily hit Gigs of data. This is kinda the same as digits of Pi. For Example 42pow1048576 is 1.6 MB! I don't have time nor memory to read all the numbers as one string then pick the one I want
| I think I get what you are after: simple, default formatted input. I think the reason there is no TextReader.ReadXXX() is that this is parsing, and parsing is hard: for example: should ReadFloat():
ignore leading whitespace
require decimal point
require trailing whitespace (123abc)
handle exponentials (12.3a3 parses differently to 12.4e5?)
Not to mention what the heck does ReadString() do? From C++, you would expect "read to the next whitespace", but the name doesn't say that.
Now all of these have good sensible answers, and I agree C# (or rather, the BCL) should provide them, but I can certainly understand why they would choose to not provide fragile, nearly impossible to use correctly, functions right there on a central class.
EDIT:
For the buffering problem, an ugly solution is:
static class TextReaderEx {
static public string ReadWord(this TextReader reader) {
int c;
// Skip leading whitespace
while (-1 != (c = reader.Peek()) && char.IsWhiteSpace((char)c)) reader.Read();
// Read to next whitespace
var result = new StringBuilder();
while (-1 != (c = reader.Peek()) && !char.IsWhiteSpace((char)c)) {
reader.Read();
result.Append((char)c);
}
return result.ToString();
}
}
...
int.Parse(Console.In.ReadWord())
|
2,322,402 | 2,322,477 | Are there delimiter bytes for UTF8 characters? | If I have a byte array that contains UTF8 content, how would I go about parsing it? Are there delimiter bytes that I can split off to get each character?
| Take a look here...
http://en.wikipedia.org/wiki/UTF-8
If you're looking to identify the boundary between characters, what you need is in the table in "Description".
The only way to get a high bit zero is the ASCII subset 0..127, encoded in a single byte. All the non-ASCII codepoints have 2nd byte onwards with "10" in the highest two bits. The leading byte of a codepoint never has that - it's high bits indicate the number of bytes, but there's some redundancy - you could equally watch for the next byte that doesn't have the "10" to indicate the next codepoint.
0xxxxxxx : ASCII
10xxxxxx : 2nd, 3rd or 4th byte of code
11xxxxxx : 1st byte of code, further high bits indicating number of bytes
A codepoint in unicode isn't necessarily the same as a character. There are modifier codepoints (such as accents), for instance.
|
2,322,446 | 2,322,502 | Pimpl idiom used with a class member variable | Whats the correct way of implementing this class?
//Header
#include <boost/shared_ptr.hh>
class MyClass
{
public:
static foo()
static foobar();
private:
class pimpl;
static boost::shared_ptr<pimpl> m_handle;
static bool initialized;
};
//source
namespace
{
bool init()
{
//...
// init() can't access m_handle, unless it is a friend of MyClass
// but that seems a bit "tacky", is there a better way?
}
}
class MyClass::pimpl
{
public:
~pimpl(){}
}
bool MyClass::initialized = init();
MyClass::foo()
{
//...
}
MyClass::foobar()
{
//...
}
| MyClass is a singleton -- some call it a glorified global. An oft-abused pattern. Use private ctors and a public static accessor:
MyClass {
public:
static MyClass& Instance() {
static MyClass obj;
return obj;
}
// ...
private:
MyClass() : m_handle(pimpl()), initialized(true) {}
// ...
};
|
2,322,533 | 2,322,641 | Thread-safe variables in Linux programming | I am writing a shared library that will allow linked applications to query a resource.
The resource class is implemented with only static methods (see below). It also uses a global object (well scoped in an anonymous namespace). The reason for the global variable is that I do not want to expose users of the library to the internals of the system. I suppose I could have used a pimpl idiom, but that still does not address the issue of thread safety.
The class looks something like this:
//Header
class A
{
public:
static int foo();
static double foobar();
};
// Source
namespace
{
SomeResourceObject globvar; // <- how can this variable be made thread safe ?
}
int A::foo(){}
double A::foobar(){}
Some of the applications using this library will be multithreaded and thus may call methods on A from different threads.
My question therefore is how to implement globvar so as to be threadsafe?
I am developing using gcc 4.4.1 on Ubuntu 9.10
| Wrap your objects to be operated upon in re-entrant locks wherever you access it :) There's some code in C++ here which allows you to implement a locking mechanism. Needs Boost though:
http://the-lazy-programmer.com/blog/?p=39
Seems quite cool :)
LOCK (myObject) {
do something with myObject
}
Make sure you look at the comments to see any fixes people have made to the code.
|
2,322,736 | 2,323,005 | what is the difference between function declaration and signature? | In C or C++ what is the difference between function declaration and function signature?
I know something of function declaration but function signature is totally new to me. What is the point of having the concept of function signature? What are the two concepts used for actually?
Thanks!
| A function declaration is the prototype for a function (or it can come from the function definition if no prototype has been seen by the compiler at that point) - it includes the return type, the name of the function and the types of the parameters (optionally in C).
A function signature is the parts of the function declaration that the compiler uses to perform overload resolution. Since multiple functions might have the same name (ie., they're overloaded), the compiler needs a way to determine which of several possible functions with a particular name a function call should resolve to. The signature is what the compiler considers in that overload resolution. Specifically, the standard defines 'signature' as:
the information about a function that participates in overload resolution: the types of its parameters and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared.
Note that the return type is not part of the function signature. As the standard says in a footnote, "Function signatures do not include return type, because that does not participate in overload resolution".
|
2,322,742 | 2,326,635 | How do you declare and use an overloaded pool operator delete? | I would like to know how to adapt section 11.14 of the C++-FAQ-lite to arrays.
Basically, I would want something like this:
class Pool {
public:
void* allocate(size_t size) {...}
void deallocate(void* p, size_t size) {...}
};
void* operator new[](size_t size, Pool& pool) { return pool.allocate(size); }
void operator delete[](void* p, size_t size, Pool& pool) { pool.deallocate(p, size); }
struct Foo {...};
int main() {
Pool pool;
Foo* manyFoos = new (pool) Foo [15];
/* ... */
delete [] (pool) manyFoos;
}
However, I have not been able to figure out the correct syntax to declare and call this operator delete[] (pool). Can anybody help here?
| It is impossible. Bjarne reasons that you'll never get it right figuring out the correct pool. His solution is: you must manually call all destructors and then figure out the correct pool to be able to deallocate the memory manually.
References:
Bjarne's FAQ: Is there a placement delete?
Relevant C++ standard sections:
3.7.3.2.2 Only member operator delete functions with an argument of size_t type are considered for delete expressions.
5.3.5.1 Delete expression syntax does not allow extra parameters.
|
2,322,748 | 2,322,852 | help with set & map on STL for c++ | I am taking a CS class, and most of the assignments were in java. in the last java assignment we learned collections. This assignment we are using c++ and i need to learn the STL
The required book is all in java. We were given this webpage http://www.cplusplus.com/
however, that and google is not going to get me through the assignment.
Can you recommend a good book on STL and c++? I need to learn mostly about set and map.
This assignment is about a media library(book,cd,dvd info)
we were given a skeleton program to work with and in the library class i am not sure what the set and map are actually for regarding what goes in what for the book, CD, DVD information..? can someone tell me based off of the functions what goes into what set/map?
typedef set<Item*> ItemSet;
typedef map<string,Item*> ItemMap;
typedef map<string,ItemSet*> ItemSetMap;
class Library
{
public:
// general functions
void addKeywordForItem(const Item* const item, const string& keyword);
const ItemSet* itemsForKeyword(const string& keyword) const;
void printItem(ostream& out, const Item* const item) const;
// book-related functions
const Item* addBook(const string& title, const string& author, int const nPages);
const ItemSet* booksByAuthor(const string& author) const;
const ItemSet* books() const;
// music-related functions
const Item* addMusicCD(const string& title, const string& band, const int nSongs);
void addBandMember(const Item* const musicCD, const string& member);
const ItemSet* musicByBand(const string& band) const;
const ItemSet* musicByMusician(const string& musician) const;
const ItemSet* musicCDs() const;
// movie-related functions
const Item* addMovieDVD(const string& title, const string& director, const int nScenes);
void addCastMember(const Item* const movie, const string& member);
const ItemSet* moviesByDirector(const string& director) const;
const ItemSet* moviesByActor(const string& actor) const;
const ItemSet* movies() const;
};
| Okay, the key question is which operations you need to support. The operations dictate which data structure you should use.
For example, for books you've got:
const Item* addBook(const string& title, const string& author, int const nPages);
const ItemSet* booksByAuthor(const string& author) const;
const ItemSet* books() const;
This means that you need sets of books: all books and by author. Therefore you need a map which maps author to the set of books having that author.
Your functions might look like this:
ItemSet allBooks;
ItemSetMap allBooksByAuthor;
...
const Item* addBook(const string& title, const string& author, int const nPages)
{
BookItem* item = new BookItem(...);
allBooks.insert(item); // add to set of all books
allBooksByAuthor[author].insert(item); // add to set of books by this author
return item;
}
const ItemSet* booksByAuthor(const string& author) const
{
return allBooksByAuthor[author];
}
const ItemSet* books() const
{
return allBooks;
}
|
2,322,831 | 2,322,874 | load XML from variable, not File | I'm trying to parse XML data stored in a variable, not a file. The reason for this is that program x replies to program y in XML, so it would seem to be best to directly parse the XML from the variable.
So far I have tried to do this in TinyXML, but I don't see an interface to load from a variable.
It's basically the opposite of TinyXML: Save document to char * or string, instead of saving to char, I want to load from char(or string)
For example instead of the following:
TiXmlDocument doc( "demo.xml" );
doc.LoadFile();
something like
doc.LoadVar(char*)
I also checked out RapidXML, but I also can't seem to find documentation to load from a variable.
Thanks
| If you already have the document in a string why not simply call the TiXmlDocument::Parse method and be done?
|
2,322,876 | 2,322,910 | debugging information cannot be found or does not match visual studio's | I copied an existing project and renamed the folder. Now I get this error when I try to compile the application
debugging information cannot be found or does not match. No symbols loaded.
Do you want to continue debugging ?
If I click yes, it compiles and runs fine. But now I have to deal with that message. Just curious about what I change in the projects properties to get it to stop.
| The main reason is that you don't have a matching pdb and exe.
Some possible solutions:
You are compiling in release instead of debug
You need to clean/build or rebuild
You don't have your pdb files being generated in the same directory as the exe
You have a mismatching pdb, maybe the copied source is newer than today's date and something isn't building properly.
Try cleaning out all debug object files
You are attaching to a process that you started from a different location from where your build exe and pdb exist
Restart Visual Studio
|
2,322,931 | 2,323,727 | dylib on Snow Leopard "file is not of required architecture" | I have compiled opencv on snow leopard and it says it compiled correctly, however when I try to compile my sample program against it, I get output like:
g++ -o tm_scons template.o -L/opencv/opencv/build/lib -lcxcore -lcv -lcvaux -lhighgui -lml
ld: warning: in /opencv/opencv/build/lib/libcxcore.dylib, file is not of required architecture
ld: warning: in /opencv/opencv/build/lib/libcv.dylib, file is not of required architecture
ld: warning: in /opencv/opencv/build/lib/libcvaux.dylib, file is not of required architecture
ld: warning: in /opencv/opencv/build/lib/libhighgui.dylib, file is not of required architecture
ld: warning: in /opencv/opencv/build/lib/libml.dylib, file is not of required architecture
Is this likely a problem with my compilation of OpenCV or of my app that is using it?
| As it turns out the magic was using -m32 and switching to the /usr/bin/g++-4.0 compiler.
Ugh....
|
2,322,934 | 2,322,950 | How to make a console program doesn't have console window | I'm writing a console program.
The program doesn't print anything.
So, it doesn't need to a console window.
I tried to call FreeConsole() function at program starting point.
When I execute the program from windows explorer, a console window appears and then disappears.
But I wish the console window never appears.
How can I do that?
Thanks in advance.
| If you are using Visual Studio .Net then create a normal console application and change the output type to Windows application.
|
2,323,189 | 2,323,224 | How is a reference different from a pointer in implementation? |
Possible Duplicate:
Difference between pointer variable and reference variable in C++
I am reading about the book "Inside the C++ Object Model" by Stanley Lippman. What puzzles me is the difference between a "reference" of an object and a "pointer" to an object. I know that a reference must be initialized when declared, while a pointer could be left for later initialization. But I want to know the physical implementation difference between them.
Why should there be the "reference" mechanism; isn't it overlapping the function of a pointer? Under what circumstance should we use reference other than pointer? Many thanks.
10:48 AM 11/20/2021
Reference is from the semantic perspective.
Pointer is from the implementation perspective.
It's kind of like the relation between what and how.
| Most references are implemented using a pointer variable i.e. a reference usually takes up one word of memory. However, a reference that is used purely locally can - and often is - eliminated by the optimizer. For example:
struct S { int a, int b[100]; };
void do_something(const vector<S>& v)
{
for (int i=0; i<v.size(); ++i) {
int*& p = v[i].b;
for (int j=0; j<100; ++j) cout <<p[j];
}
In this case, p needs not be stored in memory (maybe it just exists in a register, maybe it disappears into the instructions).
|
2,323,225 | 2,323,241 | C++ Copy constructor, temporaries and copy semantics | For this program
#include <iostream>
using std::cout;
struct C
{
C() { cout << "Default C called!\n"; }
C(const C &rhs) { cout << "CC called!\n"; }
};
const C f()
{
cout << "Entered f()!\n";
return C();
}
int main()
{
C a = f();
C b = a;
return 0;
}
the output I get is:
Entered f()!
Default C called!
CC called!
Since f() is returning by value, it should return a temporary. As T a = x; is T a(x);, wouldn't it call the copy constructor for the construction of a, with the temporary passed-in as its argument?
|
Since f() is returning by value, it should return a temporary. As T a = x; is T a(x);, wouldn't it call the copy constructor for the construction of a, with the temporary passed-in as its argument?
Look up Return Value Optimization. This is turned on by default. If you are on Windows using MSVC 2005+ you can use /Od to turn this off and get the desired result (or -fno-elide-constructors on GCC). Also, for MSVC see this article.
12.8 Copying class objects
15 When certain criteria are met, an
implementation is allowed to omit the
copy construction of a class object,
even if the copy constructor and/or
destructor for the object have side
effects. In such cases, the
implementation treats the source and
target of the omitted copy operation
as simply two different ways of
referring to the same object, and the
destruction of that object occurs at
the later of the times when the two
objects would have
been destroyed without the
optimization.115 This elision of copy
operations is permitted in the
following circumstances (which may be
combined to eliminate multiple
copies):
— in a return statement in a
function with a class return type,
when the expression is the name of a
non-volatile automatic object with the
same cv-unqualified type as the
function return type, the copy
operation can be omitted by
constructing the automatic object
directly into the function’s return
value
— in a throw-expression, when
the operand is the name of a
non-volatile automatic object, the
copy operation from the operand to the
exception object (15.1) can be omitted
by constructing the automatic object
directly into the exception object
—
when a temporary class object that has
not been bound to a reference (12.2)
would be copied to a class object with
the same cv-unqualified type, the copy
operation can be omitted by
constructing the temporary object
directly into the target of the
omitted copy
— when the
exception-declaration of an exception
handler (Clause 15) declares an object
of the same type (except for
cv-qualification) as the exception
object (15.1), the copy operation can
be omitted by treating the
exception-declaration as an alias for
the exception object if the meaning of
the program will be unchanged except
for the execution of constructors and
destructors for the object declared by
the exception-declaration.
Note: Emphasis mine
|
2,323,239 | 2,323,252 | How about defining a class but not make any instance of it? | I am learning some COM code and the following code puzzled me.
STDMETHODIMP _(ULONG) ComCar::Release()
{
if(--m_refCount==0)
{
delete this; // how could this "suicide" deletion be possible?
return 0;
}
return m_refCount;
}
Yes. this is the similar code from here. And there I askes about how could a memeber method delete its belonging object. Now I am thinking about these 2 scenarios.
1- If I define a class without making an instance of it. Would any data related to this type exist in runtime?
2- If I only make 1 instance of the class and make the very single object commit suicide via the above code. After the object is deleted, where could the object's methods stay? Or am I paying too much attention to the encapsulation illusion?
I am wondering whether class methods are first name-mangled and then stored in the code/text segment of the program without regard to the existence of any object of its type. So the class methods exist as long as you define them.
|
1- If I define a class without making an instance of it. Would this type exist in runtime?
Edit post OP's edit and gnud's comment:
A class is an user defined type. The type will be available as will be a float type even if you don't use any float in your code. The type information will be present. Particularly as gnud points out, if this is an abstract base class, you'd not be able to create any objects of that type but have derived class objects. The base class's member information will be suitably copied/updated to the derived class objects (provided you have appropriate ctors defined of course).
2- If I only make 1 instance of the
class and make the very single object
commit suicide via the above code.
After the object is deleted, where
could the method stay?
Methods are portions of executable code. Class objects have a table of all member function pointers. This table is updated when the object is created to point to the appropriate region of the binary. When the object is deleted, the binary remains, without a way to access it.
Edit: More on delete this which is perfectly legal: This is FAQ 16.15. Further, note that this is useful only in very few instances -- a reference counted object is one such (as you show in your code).
|
2,323,413 | 2,323,461 | Accessing member variables through boost lambda placeholder | I'm trying to print the second member variable of all items in an stl map using a lambda expression
map<int, int> theMap;
for_each(theMap.begin(), theMap.end(),
cout << bind(&pair<int, int>::second, _1) << constant(" "));
but this is not compiling. I essentially want to de-reference the placeholder. Any idea what I'm missing here?
Thanks in advance!
| std::map will add const to its key; this is to prevent messing up the ordering. Your pair should be:
std::pair<const int, int>
Like dirkgently suggests, use the value_type to always get the correct type. The verbosity is alleviated with a typedef:
typedef std::map<int, int> int_map;
int_map::value_type::second
|
2,323,490 | 2,323,518 | Non-recursive mutex ownership | I read this answer on SO:
Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex.
I'm confused by the last statement. Can one thread lock a mutex and another different thread unlock that mutex? I thought that same thread should be the only one able to unlock the mutex? Or is there any specific mutex that allows this? I hope someone can clarify.
| Non-recursive mutex
Most mutexes are (or at least should be) non-recursive. A mutex is an object which can be acquired or released atomically, which allows data which is shared between multiple threads to be protected against race conditions, data corruption, and other nasty things.
A single mutex should only ever be acquired once by a single thread within the same call chain. Attempting to acquire (or hold) the same mutex twice, within the same thread context, should be considered an invalid scenario, and should be handled appropriately (usually via an ASSERT as you are breaking a fundamental contract of your code).
Recursive mutex
This should be considered a code smell, or a hack. The only way in which a recursive mutex differs from a standard mutex is that a recursive mutex can be acquired multiple times by the same thread.
The root cause of the need for a recursive mutex is lack of ownership and no clear purpose or delineation between classes. For example, your code may call into another class, which then calls back into your class. The starting class could then try to acquire the same mutex again, and because you want to avoid a crash, you implement this as a recursive mutex.
This kind of topsy-turvy class hierarchy can lead to all sorts of headaches, and a recursive mutex provides only a band-aid solution for a more fundamental architectural problem.
Regardless of the mutex type, it should always be the same thread which acquires and releases the same mutex. The general pattern that you use in code is something like this:
Thread 1
Acquire mutex A
// Modify or read shared data
Release mutex A
Thread 2
Attempt to acquire mutex A
Block as thread 1 has mutex A
When thread 1 has released mutex A, acquire it
// Modify or read shared data
Release mutex A
It gets more complicated when you have multiple mutexes that can be acquired simultaneously (say, mutex A and B). There is the risk that you'll run into a deadlock situation like this:
Thread 1
Acquire mutex A
// Access some data...
*** Context switch to thread 2 ***
Thread 2
Acquire mutex B
// Access some data
*** Context switch to thread 1 ***
Attempt to acquire mutex B
Wait for thread 2 to release mutex B
*** Context switch to thread 2 ***
Attempt to acquire mutex A
Wait for thread 1 to release mutex A
*** DEADLOCK ***
We now have a situation where each thread is waiting for the other thread to release the other lock -- this is known as the ABBA deadlock pattern.
To prevent this situation, it is important that each thread always acquires the mutexes in the same order (e.g. always A, then B).
|
2,323,516 | 2,323,605 | Unsigned modulos: alternative approach? | I'm in a need to optimize this really tiny, but pesky function.
unsigned umod(int a, unsigned b)
{
while(a < 0)
a += b;
return a % b;
}
Before you cry out "You don't need to optimize it", please keep in mind that this function is called 50% of the entire program lifetime, as it's being called 21495808 times for the smallest test case benchmark.
The function is already being inlined by the compiler so please don't offer to add the inline keyword.
| This should do it:
unsigned umod(int a, unsigned b)
{
if (a < 0)
{
unsigned r = (-a % b);
if (r)
return b - r;
else
return 0;
}
else
return a % b;
}
Tested to match original. Limitation is that a > INT_MIN on 2s complement machines.
|
2,323,591 | 2,323,611 | The method used in 3rd-party garbage collector | I am writing to clarify some comments on this website.
1) I know that C++ has no garbage collector. One said that C++ was invented before the idea of garbage collector, so that's the reason. Is that true? I think it makes sense.
2) Whenever garbage collector was discussed, smart point(such as boost::share_ptr) was brought out to be a way. I was once convinced that reference counting is one way to implement garbage collector, but some said, smart point is not an implementation of garbage collector. What's the case?
3) Some said why garbage collector was not included in C++ is because it was hard and a lot of problem couldn't be solved. However, somebody else said that there were 3rd-party garbage collector were available, no matter it is commercial or for-free. So how does these 3rd-party deal with the problems?
I am grateful if anybody could clarify my confusions.
Thanks so much!
|
no, garbage collection is far older than C++ (many Lisp versions had it in the '60s, in particular).
reference counting is a way to implement garbage collection, but it's quite poor performance-wise (the new Unladen Swallow project, to accelerate the CPython interpreter, includes moving from reference counting to a better garbage collection implementation -- a substantial performance boost).
the Boehm collector for C and C++ uses a conservative approach: briefly, anything that looks like an address is taken to be one (so whatever it might "point to" is not collected). Read the page at the URL I've given, and its outgoing links, for much more information on the subject.
|
2,323,613 | 2,340,250 | What are good online introductions to testing and Test Driven Development? | I'm looking for an online introduction to unit testing and TDD. I have virtually no experience with TDD, unit testing, or any other agile methodology. My development environment is C++ on Linux. If there's a quality introduction to unit testing and TDD that uses C++ as the example language, that'd be great. If not then a general introduction in any old language and a more advanced tutorial using C++ would suffice.
| For the introduction to TDD, the bowling game episode is very nice, as it demonstrate how the tests drive the design. Then, here are tutorials focusing on C++ frameworks for CppUnit, Boot::Test and CppCheck.
To help choosing a framework, Noel LLopis explored this jungle, albeit a long time ago, especially it dosen't mention GoogleTest or you can refer to this question.
Oh, and BTW, [automated] unit testing and TDD can be applied even in non agile environment.
|
2,323,627 | 2,323,639 | C++ functions taking values, where they should be taking references | I'm just learning c++, and coming from c, some function calls I'm seeing in the book confuse me:
char a;
cin.get(a);
In C, this couldn't possibly work, if you did that, there would be no way to get the output, because you are passing by value, and not by reference, why does this work in c++? Is referencing and dereferncing made implicit (the compiler knows that cin.get needs a pointer, so it is referenced)?
| C++
This would work in C++ because the function signature for get() is probably this:
void get(char& a); // pass-by-reference
The & symbol after char denotes to the compiler than when you pass in a char value, it should pass in a reference to the char rather than making a copy of it.
What this essentially means is that any changes made within get() will be reflected in the value of a outside the method.
If the function signature for get() was this:
void get(char a); // pass-by-value
then a would be passed by value, which means a copy of a is made before being passed into the method as a parameter. Any changes to a would then only be local the method, and lost when the method returns.
C
The reason why this wouldn't work in C is because C only has pass-by-value. The only way to emulate pass-by-reference behaviour in C is to pass its pointer by value, and then de-reference the pointer value (thus accessing the same memory location) when modifying the value within the method:
void get(char* a)
{
*a = 'g';
}
int main(int argc, char* argv[])
{
char a = 'f';
get(&a);
printf("%c\n", a);
return 0;
}
Running this program will output:
g
|
2,323,736 | 2,324,127 | Remove dependancy constants from enum definition | I am trying to safely remove a dependency from my project by using opaque structures and forward declarations but like most I am still stuck on my enums.
The header file dependency I am trying to remove from my header files has defined constants that I want to set my enumeration's values to. Something like this
// depends header
#define DEP_TYPE_ONE 1
#define DEP_TYPE_TWO 2
#define DEP_TYPE_THREE 3
// My header
enum TYPES
{
T_ONE = DEP_TYPE_ONE,
T_TWO = DEP_TYPE_TWO,
T_THREE = DEP_TYPE_THREE
}
I am trying to figure out a way to not have to include the depends header in my header.
Odds are the answer is probably simply 'you can't do that' but I just want to ask because a solution would make my life infinity easier.
| How about removing the include of the depends header, hard code the values, and comment the dependency:
// my_header.h
// NOTE: Enumerands must be in sync with symbols defined in depends.h
enum TYPES
{
T_ONE = 1, // DEP_TYPE_ONE
T_TWO = 2, // DEP_TYPE_TWO
T_THREE = 3 // DEP_TYPE_THREE
};
To allay fears about the values getting out of sync, you can have another header or source file (one that users of your class or API don't get) that contains one or more compile-time asserts:
// Some non-distributed file
#include <depends.h>
#include "my_header.h"
// Compile-time assertion macro
#define compile_time_assert(cond, msg) \
typedef char msg[(cond) ? 1 : -1]
// Check assumptions at compile time...
compile_time_assert(T_ONE==DEP_TYPE_ONE, ValueOutOfSync1);
compile_time_assert(T_TWO==DEP_TYPE_TWO, ValueOutOfSync2);
.
.
.
This would give you a compile time error if the values ever get out of sync.
For more info on the compile_time_assert macro, see: http://www.embedded.com/columns/programmingpointers/164900888?_requestid=379501
|
2,323,751 | 2,323,870 | Eliminate repetition in C++ code? | Given the following:
StreamLogger& operator<<(const char* s) {
elements.push_back(String(s));
return *this;
}
StreamLogger& operator<<(int val) {
elements.push_back(String(asString<int>(val)));
return *this;
}
StreamLogger& operator<<(unsigned val) {
elements.push_back(String(asString<unsigned>(val)));
return *this;
}
StreamLogger& operator<<(size_t val) {
elements.push_back(String(asString<size_t>(val)));
return *this;
}
is there a way to eliminate repetition? I want to use templates, but I only want it for the following types: const char* int, unsigned, and size_t
| Really, in "vanilla" C++ you either write the by hand, for specific types, or you use a template like dirkgently suggested.
That said, if you can use Boost this does what you want:
template <class T>
StreamLogger& operator<<(T val)
{
typedef boost::mpl::vector<const char*, int,
unsigned, size_t> allowed_types;
BOOST_MPL_ASSERT_MSG(boost::mpl::contains<allowed_types, T>::value,
TYPE_NOT_ALLOWED, allowed_types);
// generic implementation follows
elements.push_back(boost::lexical_cast<std::string>(val));
return *this;
}
This will generate a compile-time error with the message TYPE_NOT_ALLOWED embedded in it if the type being compiled is not contained in the typelist.
Also, since this answer requires Boost I just used lexical_cast. You'll note you're repeating that code, and that's bad. Consider wrapping that functionality into a function.
If you aren't able to use Boost, you can simulate this pretty easily with some type traits:
template <typename T, typename U>
struct is_same
{
static const bool value = false;
};
template <typename T>
struct is_same<T, T>
{
static const bool value = true;
};
template <bool>
struct static_assert;
template <>
struct static_assert<true> {}; // only true is defined
// not the best, but it works
#define STATIC_ASSERT(x) static_assert< (x) > _static_assert_
template <class T>
StreamLogger& operator<<(T val)
{
STATIC_ASSERT(is_same<const char*, T>::value ||
is_same<int, T>::value ||
is_same<unsigned, T>::value ||
is_same<size_t, T>::value);
// generic implementation follows
elements.push_back(boost::lexical_cast<std::string>(val));
return *this;
}
This will also generate a compile-time error if the assert fails, though the code isn't as sexy. :( <- Not sexy
|
2,323,927 | 2,323,935 | Why can't I initialize my static data member in my constructor | I read the answer in parashift but I need bit details as to why compiler won't allow to define static member variable in constructor.
| static member variables are not associated with each object of the class. It is shared by all objects. If you initialize in ctor then it means that you are trying to associate with a particular instance of class. Since this is not possible, it is not allowed.
|
2,323,929 | 2,323,967 | istringstream - how to do this? | I have a file:
a 0 0
b 1 1
c 3 4
d 5 6
Using istringstream, I need to get a, then b, then c, etc. But I don't know how to do it because there are no good examples online or in my book.
Code so far:
ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file,line);
iss >> id;
This prints "a" for id both times. I don't know how to use istringstream obviously and I HAVE to use istringstream. Please help!
| ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file,line);
istringstream iss2(line);
iss2 >> id;
getline(file,line);
iss.str(line);
iss >> id;
istringstream copies the string that you give it. It can't see changes to line. Either construct a new string stream, or force it to take a new copy of the string.
|
2,323,940 | 2,323,969 | Does "Return value optimization" cause undefined behavior? | Reading this Wikipedia article pointed by one of the repliers to the following question:
C++ Copy constructor, temporaries and copy semantics
I came across this line
Depending on the compiler, and the compiler's settings, the resulting program may display any of the following outputs:
Doesn't this qualify for undefined behavior? I know the article says Depending on the compiler and settings but I just want to clear this.
| No, it's not undefined behavior. Undefined behavior has a specific definition in the standard (mostly: "behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements.") In this case, the behavior is unspecified, but not undefined.
The difference is that any execution of anything with undefined behavior makes all the behavior of your program undefined (i.e. anything can happen). With this particular unspecified behavior, only one of two things can happen: either the copy constructor executes, or it doesn't.
|
2,324,325 | 2,324,376 | linked list and Red/Black tree in c# - reference problem? | I'm pretty new to c#, and i'm trying to understand something pretty basic.
I want to implement a RBTree and a linked list , so i create :
public class RBTreeNode
{
// PROPERTIES
public RBTreeNode left;
public RBTreeNode right;
public RBTreeNode parent;
public String Color;
public Int Key;
}
List<RBTreeNode> deleteList = new List<RBTreeNode>();
During the running of my program i iterate through the tree, taking some nodes (depending on the value) , and adding them to deleteList.
the thing that i can't set my mind to, is if for example i have RBTreeNode X , and i do
X.left = null. the thing i want to happen is nulling X's left child (without affecting X.left RBTreeNode , but what i think will happen here is that indeed X.left will become null, but the X.left RBTreeNode object will become also null. which is not what i want. (if it's copied to deleteList , it will become null, which is wrong)
I want to be able to do the same thing i do with c++ using pointers.
In c++ i might do it like :
public class RBTreeNode
{
// PROPERTIES
public RBTreeNode* left;
public RBTreeNode* right;
public RBTreeNode* parent;
public std::string Color;
public int Key;
}
For example :
RBTreeNode* tenp = X->left;
X->left = null; //(i think in c# it will turn temp here to null to - of course without pointers)
temp->right = &X;
Any tips/explanations ?
| No, you're fine. X.left is just a variable. Setting it to null just sets the value of that variable to null, it does nothing to the object that it used to refer to.
There's really no such concept as setting an object to null in C#.
I have an article about value and reference types in C# that you may find useful.
|
2,324,602 | 2,340,194 | "No source available for main()" error when debugging simple C++ in Eclipse with gdb | I'm having trouble debugging a C++ program in Eclipse (the latest RC of Helios, updated with latest CDT from within itself) on OSX.
The program is very simple (esentially Lesson 2 from NeHe's OpenGL tutorials), consisting of one cpp file and, using OpenGL and Cocoa frameworks, and linking with libSDL.a and libSDLmain.a.
The structure of the project is very simple: the source file(s) are in a subdirectory of the project called src/ and the executable is built to the project's root directory.
The problem is that whenever I try to add breakpoints and debug it, the breakpoints seem to get hit perfectly but no source is displayed - instead I just get a "No source available for main()" error in the code window.
The compiler flags have optimisations set to none, and both the compiler and linker have the debug symbols flag set (-g).
The debugging setting in Eclipse is set to "Standard spawn progess" and the debugger is set to "gdb".
Now the strangest thing is that if I try to debug the exact same executable - ie. the exact same one that was built by Eclipse - using gdb from the Terminal (shell) then everything works fine. Breakpoints are hit, source code is displayed, no problems at all.
I've made sure that both Eclipse and the shell are using the same gdb executable, and they are (it's /usr/bin/gdb).
Now I may be wrong, but this all suggests to me that there can't be a problem with the compiler and linker flags (because the same executable is debuggable from the shell), so presumably the problem must be with how gdb is being invoked from within Eclipse? Perhaps when run from Eclipse gdb is picking up different config files or something than when it's run from the shell? (Anyone know?)
I'd really appreciate any help with this because it's slowly driving me loopy!
Please let me know if there are any other details that would be useful - exact version numbers of Eclipse/cdt/gdb, exact linker/compiler command lines, etc. - and I'll very gladly update this post with them.
Many thanks in advance,
thoughton.
--- edited @ "14 hours ago" ---
I tried the "add filesystem path" (with "search sub-folders") option, but that didn't work. I also tried creating a new completely flat project, but that didn't work either.
I even tried getting a Galileo release (eclipse-SDK-3.5.2RC4 with CDT update), but that made no difference (apart from gdb being slower to launch).
And here's something else strange I noticed: once I get the "No source available" message, if I then switch Eclipse's Console to display the "gdb" console, and also turn on "Verbose console mode" so I can communicate it, I can then issue "l" and "bt" commands and have them work succesfully, showing the correct source and stack where my breakpoint was hit. Which, correct me if I'm wrong, must mean that the information is there and gdb is being invoked correctly - so why will Eclipse not see this information?
I'm getting close to giving up on Eclipse to be honest... I came to it with such high hopes, too.
Any additional help or thoughts would be hugely appreciated.
t.
| I found the answer! And it's embarrassingly simple.
The problem was that I was using the Release version of SDL instead of the Debug version! (I had 'libsdl' from MacPorts whereas I should have had 'libsdl-devel'.)
So my generic answer is: make sure the libs you're linking against were compiled with debug flags set too, it's not always enough to just make sure your own code has them set.
|
2,324,658 | 2,324,855 | How to determine the version of the C++ standard used by the compiler? | How do you determine what version of the C++ standard is implemented by your compiler? As far as I know, below are the standards I've known:
C++03
C++98
| By my knowledge there is no overall way to do this. If you look at the headers of cross platform/multiple compiler supporting libraries you'll always find a lot of defines that use compiler specific constructs to determine such things:
/*Define Microsoft Visual C++ .NET (32-bit) compiler */
#if (defined(_M_IX86) && defined(_MSC_VER) && (_MSC_VER >= 1300)
...
#endif
/*Define Borland 5.0 C++ (16-bit) compiler */
#if defined(__BORLANDC__) && !defined(__WIN32__)
...
#endif
You probably will have to do such defines yourself for all compilers you use.
|
2,324,851 | 2,324,884 | Use rspec to test C/C++ program | Is Rspec ruby/rails specific? Is it possible to use it as a test framework for C/C++ program?
| Description of Rspec says:
RSpec is the original Behaviour Driven Development framework for Ruby.
I think that means this tool is Ruby specific. For c++ you could use Boost Test Library or other tools.
|
2,325,002 | 2,329,891 | Advantage of SQL_TXN_SERIALIZABLE over SQL_TXN_REPEATABLE_READ in DB2 and C++ | We are facing a problem in our application. We have two instances of our monitoring application. The application behaviour is as follows:
Step 1. Monitor the ftp folder in a loop
Step 2. If files are present, insert the file details to DB for the all files
Step 3. Read the file details from the DB and process it
Step 4. Once the file is selected from DB change the status to start processing so that no other process should process it.
Here we have two monitor process, two instance of same program (monitor --instance 1 && monitor --instance 2)
Here at some particular time, both process monitor1 and monitor2 reads the same data from the DB and process. Because of this, the same file is processed twice.
It is due to the delay in step 3 and step 4. Monitor1 does step 3 and before it does step 4, monitor2 also does step3 so that it was not aware that already monitor1 got the record.
Our DB is db2 and we are using SQL_TXN_READ_UNCOMMITTED isolation level in step3. I found from the IBM site that SQL_TXN_REPEATABLE_READ or SQL_TXN_SERIALIZABLE are solutions for this as this will prevent dirty read.
Which is the best option to use in our situation. I read from the net that SQL_TXN_SERIALIZABLE will slow down the database access.
If anybody has faced this problem in real time, could you share the solution.
Any thoughts/suggestions are well appreciated.
Thanks,
Mathew Liju
| You probably want to use SQL_TXN_READ_COMMITTED, not SQL_TXN_REPEATABLE_READ or SQL_TXN_SERIALIZABLE, as it offers better concurrency than the other two methods.
See the DB2 documentation on isolation levels, keeping in mind the following mapping:
CLI Name DB2 Isolation Level
------------------------ -------------------
SQL_TXN_READ_UNCOMMITTED Uncommitted Read
SQL_TXN_READ_COMMITTED Cursor Stability
SQL_TXN_REPEATABLE_READ Read Stability
SQL_TXN_SERIALIZABLE Repeatable Read
Since it sounds like you're setting a flag when one of the workers starts working on a file, talk to your DBA to find out if the DB2_EVALUNCOMMITTED registry variable has been enabled, as this may also help prevent the two threads from waiting on each other.
|
2,325,043 | 2,369,497 | boost::asio: thread local asynchronous events | I will be creating x amount of threads in my server-app. x will be the amount of cores on the machine, and these threads will be (non-hyperthread) core-bound. Naturally with this scheme I would like to distribute incoming connections across the threads with the aim of ensuring that once a connection is assigned to a thread, it will only be served out of that particular thread. How is this achieved in boost::asio ?
I am thinking: a single socket bound to an address shared by multiple io_service's where each threads gets it's own io_service. Is this line of reasoning correct ?
edit: looks like I am going to have to answer this question myself.
| Yes, your reasoning is basically correct. You would create a thread per core, an io_service instance per thread, and call io_service.run() in each thread.
However, the question is whether you'd really do it that way. These are the problems I see:
You can end up with very busy cores and idling cores depending on how the work is balanced across your connections. Micro-optimising for cache hits in a core might mean that you end up losing the ability to have an idle core do work when the "optimal" core is not ready.
At socket speeds (ie: slow), how much of a win will you get from CPU cache hits? If one connection requires enough CPU to keep a core busy and you only up as many connections as cores, then great. Otherwise the inability to move work around to deal with variance in workload might destroy any win you get from cache hits. And if you are doing lots of different work in each thread, the cache isn't going to that hot anyway.
If you're just doing I/O the cache win might not be that big, regardless. Depends on your actual workload.
My recommendation would be to have one io_service instance and call io_service.run() in a thread per core. If you get inadequate performance or have classes of connections where there is a lot of CPU per connection and you can get cache wins, move those to specific io_service instances.
This is a case where you should do profiling to see how much cache misses are costing you, and where.
|
2,325,121 | 2,325,170 | casting operator - const vs non-const | I have this code sample:
class Number
{
int i;
public:
Number(int i1): i(i1) {}
operator int() const {return i;}
};
What are the implications of removing the const modifier from the casting operator?
Does it affect auto casting, and why?
| If the conversion operator is not const, you can't convert const objects:
const Number n(5);
int x = n; // error: cannot call non-const conversion operator
|
2,325,146 | 2,346,937 | Using GDB with external libs | I'm currently debugging a project that uses an external library (LibFirm). When i call library functions, I can't really see what's going on there with gdb (i.e. I can't inspect local variables and such).
The library is open source and I compiled it myself, so I think it should be possible to let gdb look into it too. How?
What I am currently seeing is
(gdb) bt
#0 0x00994422 in __kernel_vsyscall ()
#1 0x002704d1 in *__GI_raise (sig=6)
at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#2 0x00273932 in *__GI_abort () at abort.c:92
#3 0x00269648 in *__GI___assert_fail (
assertion=0xd238f4 "_get_type_state(ctx.frame_tp) == layout_fixed",
file=0xd23458 "be/beabi.c", line=1879, function=0xd23d0d "modify_irg")
at assert.c:81
#4 0x00b219e3 in ?? () from /usr/local/lib/libfirm.so.0
#5 0x00b21df0 in be_abi_introduce () from /usr/local/lib/libfirm.so.0
#6 0x00b59b77 in ?? () from /usr/local/lib/libfirm.so.0
#7 0x00b5b4a5 in be_main () from /usr/local/lib/libfirm.so.0
#8 0x0807daa0 in main (argc=3, argv=0xbffff914) at main.cc:243
(gdb) frame 8
#8 0x0807daa0 in main (argc=3, argv=0xbffff914) at main.cc:243
243 be_main(output, "a.s");
(gdb) frame 4
#4 0x00b219e3 in ?? () from /usr/local/lib/libfirm.so.
frame 8 looks nice while frame 4 doesn't tell me anything. I added
dir /usr/local/include/libfirm
dir /home/thomas/Dev/foreign/libfirm
to my .gdbinit, so gdb should find header and source files of the lib.
| I had to use ./configure --enable-debug (CFLAGS="-g" was on by default, but it may not be in other projects, so remind this one). Furthermore, you may want to use CFLAGS="-g -O0" (instead of only -g) to keep the code readable.
|
2,325,148 | 2,327,721 | When to use signals and slots and when not to | We're using Qt that offers signals and slots which I find really convenient. However, with great power comes great responsibility and I think it's very easy too misuse this feature.
Are there any best-practices for signal-slot usage? I'm having a hard time to find some general guidelines in this manner. Some questions (I have clear opinions about, but that not all members of my team agree with):
Is it ok to use signals to report errors?
Is it ok to assume that a signal will be handled?
Can signals be used to initiate actions? E.g. signal displayInfoScreen() must be handled by a slot that shows an info screen.
Any other opinions on when signals should/shouldn't be used are very welcome!
|
Is it ok to use signals to report
errors?
Yes, for instance, see QFtp, where the done signal carries a status. It does not carry the actual error, just information that an error has occured.
Is it ok to assume that a signal will
be handled?
No. The sender can never assume that, however, your particular application can depend on it. For instance, the QAction representing File - New needs to be handled for the application to work, but the QAction object couldn't care less.
Can signals be used to initiate
actions? E.g. signal
displayInfoScreen() must be handled by
a slot that shows an info screen.
Again, yes, for instance the QAction object. But if you want to be able to reuse components, you must be careful to ensure that the actual class does not depend on it.
|
2,325,472 | 2,325,531 | Generate random numbers following a normal distribution in C/C++ | How can I easily generate random numbers following a normal distribution in C or C++?
I don't want any use of Boost.
I know that Knuth talks about this at length but I don't have his books at hand right now.
| There are many methods to generate Gaussian-distributed numbers from a regular RNG.
The Box-Muller transform is commonly used. It correctly produces values with a normal distribution. The math is easy. You generate two (uniform) random numbers, and by applying an formula to them, you get two normally distributed random numbers. Return one, and save the other for the next request for a random number.
|
2,325,616 | 4,331,392 | ReadFile, COM and NULL characters in c++ | I have a problem with ReadFile function in a virtual serial port:
char tmp[128];
int multiplo=0;
DWORD err;
COMSTAT stt;
ClearCommError(hcom, &err, &stt);
do{
if(ReadFile(hcom, tmp, stt.cbInQue, &err, NULL)){
tmp[err] = '\0';
memcpy(bfIn+multiplo, tmp, err);
multiplo = multiplo + err;
}else
return 0;
}while(err > 0);
this code works when ReadFile get valid character like 0x01, 0x02, 0x03... but there is a problem with 0x00, the code doesn't read like I expected, I try with hyperterminal and that works perfect.
I've defined in dcb structure:
dcb.fNull = false;
but still I have the same problem, any help?
| The problem seems to be not in ReadFile() but rather in your use of tmp[] as the terminating '\0' happens to be 0x00, too.
What do you mean by "doesn't read like I expected"? Can you describe the symptoms in more detail?
|
2,325,617 | 2,325,660 | How to define NULL using #define | I want to redefine NULL in my program such as
#define MYNULL ((void*)0)
But this definition is not working in the following statement:
char *ch = MYNULL;
Error : can not convert from void* to char *
What would be the best way to define NULL?
| #ifdef __cplusplus
#define MYNULL 0
#else
#define MYNULL ((void*)0)
#endif
will work in both of them.
|
2,325,686 | 2,326,092 | How to change the default *.exe icon in C/C++? | I want to change the default .exe icon to some other icon in C/C++. Does anybody know how to do that?
| Already answered.
Change app icon in Visual Studio 2005?
You have to place your .ico file in the resources folder first of course.
|
2,325,756 | 2,325,784 | generating a 3d graphics c++ | I have found an interesting application on the net and i am using it for my end year study project.
http://www.cl.cam.ac.uk/~sjeh3/wii/ the video in the link explains my goal.
But i am having issue using it. the example of rendering the trajectory on a 3d axis is using Corba (omniorb) and i believe open inventor. but there isn't any idl file. and i don't know if it's possible to use it.
My question is :
Is it possible to render a 3d real time graphics using a lib in c++ making it easy and fast to implement? i tried using matlab engine or matlab simulation with tcpip communication but i am having issues with these technics so i am searching for another way.
Does anybody have an idea ?
sincerely,
Hugo
| You might also look at SDL (which uses OpenGL).
Edit (re: comments)
For the plotting aspect, you could look at VTK and/or MayaVI (which puts a Python scripting wrapper around VTK).
|
2,325,830 | 2,371,818 | CMake compile C++ file in custom command | I'm trying to precompile a header file in GCC with the following command:
ADD_CUSTOM_COMMAND(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/all.hpp.gch
COMMAND ${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} -o ${CMAKE_BINARY_DIR}/all.hpp.gch ${CMAKE_CURRENT_SOURCE_DIR}/all.hpp
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/all.hpp
COMMENT "Generating precompiled headers"
)
However, I don't get CMAKE_CXX_FLAGS to expand into flags I've set using CMake's add_definitions(). What is the correct way of compiling in add_custom_command()?
| I don't believe that add_definitions() adds its arguments to CMAKE_CXX_FLAGS. In fact, as far as I can tell they aren't saved anywhere (apart from arguments beginning with -D or /D which get added to COMPILE_DEFINITIONS).
The simplest way to solve that would be to, whenever calling add_definitions(), to also manually add those flags to CMAKE_CXX_FLAGS.
To see what is in CMAKE_CXX_FLAGS at any point, you can do
message(STATUS ${CMAKE_CXX_FLAGS})
or check the CMakeCache.txt in the build directory (or via ccmake or cmake-gui).
|
2,325,894 | 2,328,013 | Difference between InvalidateRect and RedrawWindow | When I want to redraw a window, is there any preferred function to call between InvalidateRect and RedrawWindow?
For instance, are these two calls equal: (win would be a HWND)
RedrawWindow(win, NULL, NULL, RDW_INVALIDATE);
InvalidateRect(win, NULL, NULL);
The main question(s): When should I use one or the other? Are there any differences that happen in the background? (different WM_messages / focus / order / priorities..)
The reason that I want to redraw the window is because I send a new image to it that I want it to display, meaning the content of the window is no longer valid.
| InvalidateRect does not immediately redraw the window. It simply "schedules" a future redraw for a specific rectangular area of the window. Using InvalidateRect you may schedule as many areas as you want, making them accumulate in some internal buffer. The actual redrawing for all accumulated scheduled areas will take place later, when the window has nothing else to do. (Of course, if the window is idle at the moment when you issue the InvalidateRect call, the redrawing will take place immediately).
You can also force an immediate redraw for all currently accumulated invalidated areas by calling UpdateWindow. But, again, if you are not in a hurry, explicitly calling UpdateWindow is not necessary, since once the window is idle it will perform a redraw for all currently invalidated areas automatically.
RedrawWindow, on the other hand, is a function with a much wider and flexible set of capabilities. It can be used to perform invalidation scheduling (i.e. the same thing InvalidateRect does) or it can be used to forcefully perform immediate redrawing of the specified area, without doing any "scheduling". In the latter case calling RedrawWindow is virtually equivalent to calling InvalidateRect and then immediately calling UpdateWindow.
|
2,325,951 | 2,325,973 | How to handle signals when a Qt object isn't created through Designer? | Hi I've got a spare moment so decided to look at Qt and how easily I can port my windows applications to Qt.
My only real problem is a couple of controls that will need re-implementing under Qt. I've already handled the basic drawing of the control but my control creates a child scroll bar. The problem is that this scrollbar is created dynamically as part of my new Widget (i.e. m_Scrollbar is a member of the widget). How can I then respond to movement of the scrollbar. Under other circumstances this is easy as I'd just create an on_myscrollbar_sliderMoved function under my protected slots and handle it there. This does however rely on the QScrollBar being called myscrollbar. As I've created the object dynamically (i.e. not through designer) how do I capture this signal?
I'm guessing this is really simple and I'm missing the obvious :)
| connect( myScrollbar, SIGNAL( <signal signature>), this, SLOT( <slot signature>));
Call connect after creating the scroll bar (I presume that you need this signal handling immediately after creating the scroll bar).
I assumed myScrollbar is of type QScrollBar* and that the slot is defined as a member in your class.
When myScrollbar is destroyed, the connection is removed (disconnect is called).
See the documentation of QObject::connect and QObject::disconnect methods.
Later edit - to be more concrete, in your code it could be:
myScrollbar = new QScrollBar; // Create the scroll bar
// ... add it to the layout, etc.
// ... and connect the signal to your slot
connect( myScrollbar, SIGNAL( sliderMoved( int)), this, SLOT( handleSliderMoved( int)));
where handleSliderMoved is the slot method of your class.
|
2,325,960 | 2,326,197 | Class with pass-by-reference object gives compile error | I've got a class A defined in a separate header file. I want class B to have a reference to a object of class A stored as a variable.
Like this:
File: A.h
class A {
//Header for class A...
};
File: B.h
#include "A.h"
class B {
private:
(24) A &variableName;
public:
(36) B(A &varName);
};
When i try to compile it with g++ I get the following error:
B.h:24: error: ‘A’ does not name a type
B.h:36: error: expected `)' before ‘&’ token
Any suggestions on what I'm doing wrong? If it matters, the class A is an abstract class.
EDIT: Some typos in the code
| By me it compiles fine (as expected). I'm guessing A.h isn't being included properly. Is there another file with the same name that gets included instead? Perhaps there are #ifdefs or some such that prevent the definition of A from being seen by the compiler. To check this, I would put some sort of syntax error into A.h and see if the compiler catches it.
|
2,326,157 | 2,326,283 | make a charater follow an uneven terrain (2D) | I'd like to make a game where the terrain is not even and is based on a png. How s this done in theory, given the object's vec2 and its angle, because if for instance there is a hill, the character will rotate based on the angle of the hill. Thanks
2d like mario
| I think you are talking about a heightmap which is you PNG which is then converted to a 3D triangle mesh. You need to use the information from the mesh (or PNG color value) to calculate the current height where you should place your character.
If this is a flying character your pretty much done here, but in your case you need to calculate the normal vector of the current triangle the character is standing on. This is pretty simple using the cross product of the two triangle vectors (V2 - V1) x (V3 - V1). That should be your characters angle as well. You could maybe average this vector by including normals from the surrounding trangles as well.
Btw, when you have the normals of the triangle you can apply some basic shading to the ground as well.
Added: The OP changed the question to be a 2D problem. The above approach still works, but it much easier in 2D.
Use the height values not as triangles but as lines (silhouette) and calculate the normal of the current line instead. That is, create a vector, v, between the current height value and the next. Then the normal of that vector is n = <-v.y, v.x>. Use that as the angle of your character.
|
2,326,236 | 2,326,272 | Can objects be unwinded before they are created on stack? | We have been debugging a strange case for some days now, and have somewhat isolated the bug, but it still doesn't make any sense. Perhaps anyone here can give me a clue about what is going on.
The problem is an access violation that occur in a part of the code.
Basically we have something like this:
void aclass::somefunc() {
try {
erroneous_member_function(*someptr);
}
catch (AnException) {
}
}
void aclass::erroneous_member_function(const SomeObject& ref) {
// { //<--scope here error goes away
LargeObject obj = Singleton()->Object.someLargeObj; //<-remove this error goes away
//DummyDestruct dummy1//<-- this is not destroyed before the unreachable
throw AnException();
// } //<--end scope here error goes away
UnreachableClass unreachable; //<- remove this, and the error goes away
DummyDestruct dummy2; //<- destructor of this object is called!
}
While in the debugger it actually looks like it is destructing the UnreachableClass, and when I insert the DummyDestruct object this does not get destroyed before the strange destructor are called. So it is not seem like the destruction of the LargeObject is going awry.
All this is in the middle of production code, and it is very hard to isolate it to a small example.
My question is, does anyone have a clue about what is causing this, and what is happening? I have a quite full featured debugger available (Embarcadero RAD studio), but now I am not sure what to do with it.
Can anyone give me some advise on how to proceed?
Update:
I placed a DummyDestruct object beneath the throw clause, and placed a breakpoint in the destructor. The destructor for this object is entered (and its only us is in this piece of code).
| With the information you have provided, and if everything is as you state, the only possible answer is a bug in the compiler/optimizer. Just add the extra scope with a comment (This is, again, if everything is exactly as you have stated).
|
2,326,376 | 2,326,397 | Deque of user-defined structures | I've got a user-defined structure struct theName and I want to make a deque of these structures (deque<theName> theVar). However when I try to compile I get this error:
In file included from main.cpp:2:
Logger.h:31: error: ISO C++ forbids declaration of ‘deque’ with no type
Logger.h:31: error: expected ‘;’ before ‘<’ token
Why can't I do it this way?
File: Logger.h
#ifndef INC_LOGGER_H
#define INC_LOGGER_H
#include <deque>
#include "Motor.h"
struct MotorPoint {
double speed;
double timeOffset;
};
class Logger{
private:
Motor &motor;
Position &position;
double startTime;
(31) deque<MotorPoint> motorPlotData;
double getTimeDiff();
public:
Logger(Motor &m, Position &p);
//etc...
};
#endif
| The namespace of deque is not defined:
std::deque<MotorPoint> motorPlotData;
or
using namespace std;
// ...
deque<MotorPoint> motorPlotData;
|
2,326,460 | 2,326,554 | Can I ask VC++ linker to ignore unresolved externals? | I'm trying to build a very complex open-source project with VC++. The project consists of dozens of libraries and one executable depending on those libraries.
For some reasons VC++ linker doesn't want to see about 40 functions implemented in one of those libraries and reports "unresolved external reference" on each, so I can't link. I don't want to waste time resolving the problem - those functions are likely never called.
I'd like to just ask the linker to link what it sees and insert some reasonable error handling (like reporting an error and terminating the program) instead of missing functions. How can I do that?
| You can use the /FORCE:UNRESOLVED linker option.
The documentation for that contains the rather understated warning:
A file created with this option may
not run as expected.
In pratice, there'll be no error handling - just a crash.
|
2,326,586 | 2,326,707 | How to force template function overload for boost::bind? | I'm trying to create predicate for std::find_if by using boost::bind together with boost::contains (from boost/algoritm/string library).
Following snippet shows two ways how I'm trying to accomplish this.
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <string>
int main(int argc, char** argv) {
std::string s1("hello mom");
std::string s2("bye mom");
boost::function<bool (std::string, std::string)> f = &boost::contains<std::string, std::string>;
std::cout << s1 << " contains " << "hello, " << std::boolalpha << f(s1, "hello") << std::endl;
std::cout << s2 << " contains " << "hello, " << std::boolalpha << f(s2, "hello") << std::endl;
boost::function<bool (std::string)> contain_hello = boost::bind(boost::contains<std::string, std::string>, _1, std::string("hello"));
std::cout << s1 << " contains " << "hello, " << std::boolalpha << contain_hello(s1) << std::endl;
std::cout << s2 << " contains " << "hello, " << std::boolalpha << contain_hello(s2) << std::endl;
return EXIT_SUCCESS;
}
When compiling this code with g++ 3.4.5 I'm getting following output.
error: conversion from `<unresolved overloaded function type>' to non-scalar type `boost::function<bool ()(std::string, std::string), std::allocator<void> >' requested
error: no matching function for call to `bind(<unresolved overloaded function type>, boost::arg<1>&, std::string)'
When I switch to boost::icontains which has only one overload everyting works fine.
I know how to solve similar situation when there are multiple overloads of non-template function.
Can someone help me write this correctly? Or should I write my own compare function?
| You need to write static_cast<bool(*)(const std::string&, const std::string&)>(&boost::contains<..>) to resolve the overload.
Yes, this is a royal pain with templates and overloading. Libs written with OOP and overloading in mind are difficult to use with templates and boost::bind.
We all wait for C++0x lambda expressions, which ought to resolve things better.
|
2,326,588 | 2,326,670 | Boost asio io_service dispatch vs post | Can anyone tell me the difference between io_service dispatch and post? It was not clear to me what is more suitable for my problem.
I need to invoke a handler inside another handler and I don't know what invoker to use.
| Well, it depends on the context of the call, i.e. is it run from within the io_service or without:
post will not call the function directly, ever, but postpone the call.
dispatch will call it rightaway if the dispatch-caller was called from io_service itself, but queue it otherwise.
So, it depends on the function calling post/dispatch was called, and if the given handler can be called straight away or not.
What this means:
... is that dispatch might eventually call your code again (naturally, this depends on your app and how you chain calls), but in general you should make sure your callback is re-entrant if you use dispatch.
dispatch is thus faster, as it avoids queueing the call if possible. It comes with some caveats, so you might want needs to use post occasionally, or always (if you want to play it safe and can afford it).
Update
To incorporate some from @gimpf 's deleted answer, an older boost version had this implementation of dispatch (my comments):
template <typename Handler>
void dispatch(Handler handler)
{
if (call_stack<win_iocp_io_service>::contains(this)) // called from within io_service?
boost_asio_handler_invoke_helpers::invoke(handler, &handler); // invoke rightaway
else
post(handler); // queue
}
|
2,326,704 | 2,326,969 | Isn't a pointer just a reference when you don't dereference it? | Isn't a pointer just a reference when you don't de-reference it?
#include "stdafx.h"
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
std::list<int>* user_defined_func( ) {
std::cout << "BEGIN: user_defined_func" << std::endl;
std::list<int>* l = new std::list<int>;
l->push_back(8);
l->push_back(0);
std::cout << "END: user_defined_func" << std::endl;
return l;
}
bool validate_list(std::list<int> &L1)
{
std::cout << "BEGIN: validate_list" << std::endl;
std::list<int>::iterator it1 = L1.begin();
for(; it1 != L1.end(); ++it1)
{
if(*it1<= 1){
std::cout << "Validation failed because an item in the list was less than or equal to 1." << std::endl;
std::cout << "END: validate_list" << std::endl;
return false;
}
}
std::cout << "Test passed because all of the items in the list were greater than or equal to 1" << std::endl;
std::cout << "END: validate_list" << std::endl;
return true;
}
BOOST_AUTO_TEST_SUITE( test )
BOOST_AUTO_TEST_CASE( test )
{
std::list<int>* list1 = user_defined_func();
BOOST_CHECK_PREDICATE( validate_list, (list1) );
}
BOOST_AUTO_TEST_SUITE_END()
In the line,
BOOST_CHECK_PREDICATE( validate_list, (list1) );
above, I was told that I can't pass pointer to the function expecting reference. I thought that a pointer (that hasn't been de-referenced) was just an address (i.e. a reference). What am I missing here?
|
Isn't a pointer just a reference when
you don't de-reference it?
No, a pointer contains a value that is interpreted as a memory address. (Whether it contains a value that is actually a valid memory address is another question)
A reference is an alias, another way of referring to an existing value.
int i = 5;
int* p = &i; // The value in p is the address that i is stored at.
int& r = i; // The value in r is 5, because r is an alias of i.
// Whenever you use r, it's as if you typed i, and vice versa.
// (In this scope, anyway).
int sum = i + r; // Identical to i + i or r + i or r + r.
Edit:
since list1 is a pointer, how do I access the reference...?
You have two choices. You can derefence the pointer to get at the list it points to:
std::list<int>* list1 = user_defined_func();
std::list<int>& list1ref = *list1;
BOOST_CHECK_PREDICATE( validate_list, list1ref );
delete list1;
Of course, this could be shortened to:
std::list<int>* list1 = user_defined_func();
BOOST_CHECK_PREDICATE( validate_list, *list1 );
delete list1;
Your validation function could take a pointer instead of a reference (remember to change L1.{something} to L1->{something}):
bool validate_list(std::list<int>* L1) { ... }
|
2,326,747 | 2,326,766 | Need a cache which is shared between C++, Java and .Net Applications | Is there a caching solution which works with C++, .Net and Java all accessing and populating same data in cache? (Data is composed of simple strings only)
Longer version:
I have 4 applications which work on different areas of a problem. Two of them are developed in C++, one is a java desktop application, and another is a C# application using .Net 3.5.
Currently they get data individually in their own special ways from same source (a web-service). Programs use this data and instantiate and populate other data structures (read: simple strings using separators) which are also used by other applications.
Currently it is done through (local/remote) sockets between individual programs. The problem is that, the consumer of a specific information caches the results provided by another program for later use in its own memory. The producer also stores it in its own memory to give to another program if it requires, and so on and so on, and in the end I end up with same information copied in every program's memory.
I'm thinking if there is a middle layer of, say a cache, and every program populated and accessed the data in that cache, it'd solve memory issue. Also it'd solve the problem of every application making queries to data source for same data. I'd then have one program populating input data and others working on it. Is there any caching solution which solves this?
| Memcached works fine across independent applications.
|
2,326,791 | 2,326,924 | Two .c files have identical compilation settings - VC++ reports no error and doesn't compile one of them | I'm trying to compile a set of .c files from an open source project into a static library. I've created a VC++9 project file, set everything up as usual. I add two .c files into the project. They don't have any special compilation settings - all the settings are set at the project level and are set to default except that I turned off the precompiled headers.
I press "Build project" - VC++ says "Done", two .obj files and a .lib file are created but functions from one of the .c files are not present in the resulting .lib file.
If I add #error at the very beginning of one of the two files VC++ stops compilation and reports. But if I do the same with the other file, it just silently compiles and doesn't report the error, so it obviously doesn't compile the file and that's why the functions don't get to the .lib file.
Now I suppose that if I add some text (like #error) as the first line of a .c file the compiler would see it regardless of any preprocessor settings, compiler options, etc. Yet I have a file log.c:
#error
whatever text follows
and Visual C++ reports:
1>------ Build started: Project: MyProject, Configuration: Debug Win32 ------
1>Compiling...
1>log.c
1>Build log was saved at "file://whatever\Debug\BuildLog.htm"
1>MyProject - 0 error(s), 0 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
What is happening to the compiler and how do I make it change its mind?
| The compiler may think that the object file is up to date with the source. Is the timestamp of one of the object files in the future?
|
2,326,850 | 2,326,922 | long double to string | I'm developping in C++, using the Qt framework.
I need to convert a long double value into a string (ideally a QString, but could be something else).
So far, I always used QString::number() for numerical->string conversion, but there is no overloading for the long doubletype.
Thanks
| QString has a static function to construct a QString from a std::string, so wheaties' answer could be rewritten as:
#include <sstream>
#include <QString>
...
QString qStringFromLongDouble(const long double myLongDouble)
{
std::stringstream ss;
ss << myLongDouble;
return QString::fromStdString(ss.str());
}
|
2,327,099 | 2,327,123 | How to set up C++ Number Formatting to a certain precision? | I understand that you can use iomanip to set a precision flags for floats (e.g. have 2.0000 as opposed to 2.00).
Is there a way possible to do this, for integers?
I would like a hex number to display as 000e8a00 rather than just e8a00 or 00000000 rather than 0.
Is this possible in C++, using the standard libraries?
| With manipulators:
std::cout << std::setfill('0') << std::setw(8) << std::hex << 0 << std::endl;
Without manipulators:
std::cout.fill('0');
std::cout.width(8);
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout << 42 << std::endl;
|
2,327,316 | 2,336,237 | VS2010 RC - only 100 std::map elements in debugger | I have a small problem during debugging my App in VS 2010 RC when I want to see all the elements of std::map container.
When debugger reaches the breakpoint and I want to check the values of the map in element inspector (in 'Locals' windows and in pop-up windows after hovering the variable name with mouse as well) and I'm scrolling down the list of the elements it stops on the 100 element and I can't next elements. The map contains more than 200 elements (map's counter parameter shows this properly) but I can't view them all in the element inspector.
The problem appears even in the most simple std::map<int, int> filled with 200 int values.
Maybe this is a problem with settings, but I've tried many combinations of them and it still does not work. Maybe somebody have some ideas how to solve this.
Thank you in advance for your help.
| The display of such information is directed by the autoexp.dat file (usually located in "Program Files*"\"Microsoft Visual Studio*"\Common7\Packages\Debugger).
It seems that Microsoft added a hard coded limitation of 100 elements to the #tree operator, in order to avoid freezing Visual Studio in case of loops in the tree.
|
2,327,498 | 2,327,856 | How can I decrease complexity in library without increasing complexity elsewhere? | I am tasked to maintain and update a library which allows a computer to send commands at a hardware device and then receive its response. Currently the code is setup in such a way that every single possible command the device can receive is sent via its own function. Code repetition is everywhere; a DRY advocate's worst nightmare.
Obviously there is much opportunity for improvement. The problem is each command has a different payload. Currently the data that is to be the payload is passed to each command function in the form of arguments. It's difficult to consolidate functionality without pushing the complexity to a level that calls the library.
When a response is received from the device its data is put into an object of a class solely responsible for holding this data, they do nothing else. There are hundreds of classes which do this. These objects are then used to access the returned data by the app layer.
My objectives:
Throughly reduce code repetition
Maintain similiar level of complexity at application layer
Make it easier to add new commands
My idea:
Have one function to send a command and one to receive (the receiving function is automatically called when a response from the device is detected). Have a struct holding all command/response data which will be passed to sending function and returned by receiving function. Since each command has a corresponding enum value, have a switch statement which sets up any command specific data for sending.
Is my idea the best way to do it? Is there a design pattern I could use here? I've looked and looked but nothing seems to fit my needs.
Thanks in advance! (Please let me know if clarification is necessary)
| Well, your question implies that there is a balance between the library's complexity and the client's. When those are the only two choices, one almost always goes with making the client's life easier. However, those are rarely really the only two choices.
Now in the text you talk about a command processing architecture where each command has a different set of data associated with it. In the olden days, this would typically be implemented with a big honking case statement in a loop, where each case called a different routine with different parameters and perhaps some setup code. Grisly. McCabe complexity analysers hate this.
These days what you can do with an OO language is use dynamic dispatch. Create a base abstract "command" class with a standard "handle()" method, and have each different command inherit from it to add their own members (to represent the different "arguments" to the different commands). Then you create a big honking array of these at startup, usually indexed by the command ID. For languages like C++ or Ada it has to be an array of pointers to "command" objects, for the dynamic dispatch to work. Then you can just call the appropriate command object for the command ID you read from the client. The big honking case statement is now handled implicitly by the dynamic dispatch.
Where you can get the big savings in this scenario is in subclassing. Do you have several commands that use the exact same parameters? Make a subclass for them, and then derive all of those commands from that subclass. Do you have several commands that have to perform the same operation on one of the parameters? Make a subclass for them with that one method implemented for that operation, and then derive all those commands from that subclass.
|
2,327,552 | 2,327,624 | How to introduce boost::shared_ptr into an existing (large) C++ codebase? | I am currently trying to fix a few weaknesses in our code base by introducing the use of smart pointers. The code base is very large, and interlinked like a spider who's had one to many coffee's.
I was wondering if people had tried the before and what their approach was.
My first step has been to typedef classes, as follows.
#ifndef USE_SMART_POINTERS
#define USE_SMART_POINTERS 0
#endif
#if USE_SMART_POINTERS == 1
#include <boost/smart_ptr.hpp>
#endif
namespace ProductX
{
// forward decleration
class CTObject;
//typedefs
#if USE_SMART_POINTERS == 1
typedef boost::shared_ptr<CTObject> CTObjectPtr;
#else
typedef CTObject* CObjectPtr;
#endif
}
Now I realise this will lead to a wealth of compile areas, things like
CTObjectPtr i = NULL;
Will completly bork when smart pointers are enabled.
I was wondering if there was anything I could do at this early stage to reduce the mass of compile errors, or is it as I suspect just take things on a case by case basis.
Cheers
Rich
| Don't do this: the typedefs I mean.
Presumably the old code has at least some delete calls in it? Which would certainly fail in the case of a smart pointer.
Smart pointer certain things or not, i.e. chase a specific instance through the code base. Make it work, then move on. Good Luck!
|
2,327,848 | 2,327,867 | How does the delete in C++ know how many memory locations to delete | how does the delete operator work? Is it better then free()?. Also if u do ptr=new char[10], then delete using delete ptr, how does the pointer know how many locations to delete.
| There is only delete operator, free exist only as function. Under C++, you are encouraged to use new/delete over malloc()/free().
There is an internal "magic" in delete operator. When an array is created with new[], the size of array is stored in the metadata at the memory block. delete[] makes use of that information.
All this is of course compiler-, OS-, optimizer- and implementation-dependent.
|
2,327,879 | 2,327,915 | passing more data to std:set Comparison class | I have an std::set with the Compare class which requires additional parameter to compare keys. This variable parameter is determined in run-time and I pack it inside the set's keys just to make it accessible to Compare.
However, the parameter logically belongs to the set rather than the keys so this solution looks awkward and duplicates the same value over all keys.
Is there an elegant way to pass additional parameter to the Compare class? (I first thought about set::value_comp, but it returns compare object by value while I need a reference).
Thanks.
| The definition of std::set is:
template <
class Key,
class Traits=less<Key>,
class Allocator=allocator<Key>
>
class set
So Traits is should be your compare operator, but if would look at constructor, you can see it there again:
explicit set(
const Traits& _Comp
);
So just pass your instance to constructor. (Note it is done by copying)
|
2,327,953 | 2,327,997 | Unicode - generally working with it in C++ | Suppose we have an arbitrary string, s.
s has the property of being from just about anywhere in the world. People from USA, Japan, Korea, Russia, China and Greece all write into s from time to time. Fortunately we don't have time travellers using Linear A, however.
For the sake of discussion, let's presume we want to do string operations such as:
reverse
length
capitalize
lowercase
index into
and, just because this is for the sake of discussion, let's presume we want to write these routines ourselves (instead of grabbing a library), and we have no legacy software to maintain.
There are 3 standards for Unicode: utf-8, utf-16, and utf-32, each with pros and cons. But let's say I'm sorta dumb, and I want one Unicode to rule them all (because rolling a dynamically adapting library for 3 different kinds of string encodings that hides the difference from the API user sounds hard).
Which encoding is most general?
Which encoding is supported by wchar_t?
Which encoding is supported by the STL?
Are these encodings all(or not at all) null-terminated?
--
The point of this question is to educate myself and others in useful and usable information for Unicode: reading the RFCs is fine, but there's a 'stack' of information related to compilers, languages, and operating systems that the RFCs do not cover, but is vital to know to actually use Unicode in a real app.
|
Which encoding is most general
Probably UTF-32, though all three formats can store any character. UTF-32 has the property that every character can be encoded in a single codepoint.
Which encoding is supported by wchar_t
None. That's implementation defined. On most Windows platforms it's UTF-16, on most Unix platforms its UTF-32.
Which encoding is supported by the STL
None really. The STL can store any type of character you want. Just use the std::basic_string<t> template with a type large enough to hold your code point. Most operations (e.g. std::reverse) do not know about any sort of unicode encoding though.
Are these encodings all(or not at all) null-terminated?
No. Null is a legal value in any of those encodings. Technically, NULL is a legal character in plain ASCII too. NULL termination is a C thing -- not an encoding thing.
Choosing how to do this has a lot to do with your platform. If you're on Windows, use UTF-16 and wchar_t strings, because that's what the Windows API uses to support unicode. I'm not entirely sure what the best choice is for UNIX platforms but I do know that most of them use UTF-8.
|
2,328,031 | 2,328,526 | g++ fails mysteriously only if a .h is in a certain directory | I'm experiencing an extremely weird problem in a fresh OSX 10.4.11 + Xcode 2.5 installation. I've reduced it to a minimal test case. Here's test.cpp:
#include "macros.h"
int main (void)
{
return 1;
}
And here's macros.h:
#ifndef __JUST_TESTING__
#define __JUST_TESTING__
template<typename T> void swap (T& pT1, T& pT2)
{
T pTmp = pT1;
pT1 = pT2;
pT2 = pTmp;
}
#endif //__JUST_TESTING__
This compiles and works just fine if both files are in the same directory. HOWEVER, if I put macros.h in /usr/include/gfc2 (it's part of a custom library I use) and change the #include in test.cpp, compilation fails with this error :
/usr/include/gfc2/macros.h:4: error: template with C linkage
I researched that error and most of the comments point to a "dangling extern C", which doesn't seem to be the case at all.
I'm at a complete loss here. Is g++ for some reason assuming everything in /usr/include/gfc2 is C even though it's included from a .cpp file that doesn't say extern "C" anywhere?
Any ideas?
EDIT : It does compile if I use the full path in the #include, ie #include "/usr/include/gfc2/macros.h"
EDIT2 : It's not including the wrong header. I've verified this using cpp, g++ -E, and renaming macros.h to foobarmacros.h
| G++ may well indeed be assuming that everything in /usr/include is C. Try compiling your code with -E and studying the line markers in the preprocessor output:
g++ -E test.cpp | grep '^#'
You'll likely see things like
# 1 "/usr/include/gfc2/macros.h" 1 3 4
The 4 is the preprocessor hinting to G++ that it should wrap everything in extern "C", on the supposition that your platform's ancient header files in /usr/include predate C++. See Preprocessor Output in the CPP manual.
These days G++ mostly ignores this hint, because most platforms' C headers are no longer ancient. See the NO_IMPLICIT_EXTERN_C target macro in the GCC Internals manual. But it may be that this old version of Xcode has GCC configured without NO_IMPLICIT_EXTERN_C and thus is listening to the preprocessor's hint. (This is set when GCC itself is built -- I don't think there's a command-line switch to override it.)
You may be able to work around this by wrapping the contents of your header file in extern "C++".
|
2,328,092 | 2,328,401 | I'm creating opensource GPL H264 encoding lib/app (based on x264) do I need to pay for the license? | I'm creating opensource GPL H264 encoding lib/app (based on x264) do I need to pay for the license?
| According to this blog article, the MPEG-LA specifically indicated that license fees are required even for open source software:
In response to your specific question, under the Licenses royalties are paid on all MPEG-4 Visual/AVC products of like functionality, and the Licenses do not make any distinction for products offered for free (whether open source or otherwise)…
However, like many patent-encumbered technologies, the licensing landscape is very complex and confusing (that's what lawyers do), so it's hard to say that a 2nd hand comment from an email sent by someone in the MPEG-LA organization can be considered definitive. If I were writing open source software, I'd probably just shy away from H.264 if at all possible (and maybe rely on system installed codec if that's an option). If I were writing commercial software, I'd definitely get a license, either directly or indirectly by licensing a library from an outfit that had a license.
Sorry to be absolutely no help...
|
2,328,258 | 3,512,564 | Cumulative Normal Distribution Function in C/C++ | I was wondering if there were statistics functions built into math libraries that are part of the standard C++ libraries like cmath. If not, can you guys recommend a good stats library that would have a cumulative normal distribution function? Thanks in advance.
More specifically, I am looking to use/create a cumulative distribution function.
| I figured out how to do it using gsl, at the suggestion of the folks who answered before me, but then found a non-library solution (hopefully this helps many people out there who are looking for it like I was):
#ifndef Pi
#define Pi 3.141592653589793238462643
#endif
double cnd_manual(double x)
{
double L, K, w ;
/* constants */
double const a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937;
double const a4 = -1.821255978, a5 = 1.330274429;
L = fabs(x);
K = 1.0 / (1.0 + 0.2316419 * L);
w = 1.0 - 1.0 / sqrt(2 * Pi) * exp(-L *L / 2) * (a1 * K + a2 * K *K + a3 * pow(K,3) + a4 * pow(K,4) + a5 * pow(K,5));
if (x < 0 ){
w= 1.0 - w;
}
return w;
}
|
2,328,294 | 2,328,315 | Printing the hex value of an array to a string using C++ | Using standard C++ I/O (such as std::cout), is it possible to "print" the value of an array (however long) into a string?
For example, say I have the following array:
unsigned long C = {0x497fecf2, 0xfa989ea3, 0xd594974e};
I'd like to be able to print those values into a string, and then remove the "0x" from them. From another SO question, I've found how to print hex values with cout.
Is what I'm asking possible the way I've described?
Would it be better to just go back to an old comp sci assignment for base conversions, and convert the decimal value into hex, using a lookup table to add the appropriate next hexit to the string?
| Create a std::ostringstream, and print them to it just like you could to cout. Retrieve the string with the contents with the stringstream's str() member.
|
2,328,408 | 2,328,573 | default template arguments in c++ | Suppose i have a function template StrCompare
template<typename T=NonCaseSenCompare>//NonCaseSenCompare is a user defined class look at the detailed code below.
int StrCompare(char* str1, char* str2)
{
...
}
now in the main function i write a line
char* str1="Zia";
char* str2="zia";
int result=StrCompare(str1,str2);
it should work because we have provided a default template argument, but it does'nt compiler gives the following error
no matching function for call to `StrCompare(char*&, char*&)'
Now the detailed code is given by
#include<iostream.h>
class CaseSenCompare
{
public:
static int isEqual(char x, char y)
{
return x==y;
}
};
class NonCaseSenCompare
{
public:
static int isEqual(char x,char y)
{
char char1=toupper(x);
char char2=toupper(y);
return char1==char2;
}
};
template<typename T=NonCaseSenCompare>
int StrCompare(char* str1, char* str2)
{
for(int i=0;i < strlen(str1)&& strlen(str2);i++)
{
if(!T::isEqual(str1[i],str2[i]))
return str1[i]-str2[i];
}
return strlen(str1)-strlen(str2);
}
main()
{
char* ptr1="Zia ur Rahman";
char* ptr2="zia ur Rahman";
int result=StrCompare(ptr1,ptr2);//compiler gives error on this line
cout<<result<<endl;
system("pause");
}
If I write
int result=StrCompare<>(ptr1,ptr2);
compiler gives the same error message.
| As gf and AndreyT already wrote, you can't have default template arguments with function templates. However, if you turn your comparators into function objects, you can still use default function arguments:
template<typename Comp>
int StrCompare(char* str1, char* str2, Comp = NonCaseSenCompare())
{
...
}
You can now call StrCompare() like this
StrCompare("abc","aBc",CaseSenCompare());
or like this:
StrCompare("abc","aBc"); // uses NonCaseSenCompare
A comparator would then have to look like this:
struct CaseSenCompare {
bool operator()(char x, char y) const {return x==y;}
};
Adjust StrCompare() accordingly.
|
2,328,423 | 2,351,470 | Convert IDispatch* to a string? | I am converting an old VB COM object (which I didn't write) to C++ using ATL. One of the methods, according to the IDL, takes an IDispatch* as a parameter and the documentation and samples for this method claim that you can pass either a string (which is the progid of an object that will be created and used by the control) or an IDispatch* to an object that has already been created. How on earth do I implement this in ATL?
For example, the IDL:
[id(1)] HRESULT Test(IDispatch* obj);
The samples (which are all JScript):
obj.Test("foo.bar");
or
var someObject = new ActiveXObject("foo.bar");
obj.Test(someObject);
To make matters even more bizarre the actual VB code that implements this method actually declares the 'obj' parameter as a string! However, it all seems to work.
Can you even pass a string to a COM method that takes an IDispatch*? If so, can I determine that the IDispatch* is actually a string in my C++ ATL code? Even better, if it's an IDispatch that implements a specific interface I will want to call methods on it, or instantiate an object if it's a string.
Any ideas welcome!
| Declare the method so that it takes a VARIANT argument and check the actual type at runtime.
|
2,328,486 | 2,328,643 | Overlapping labels in Qt fridge magnets example | I want to modify the fridge magnets example provided with Qt in a way that when I drag a label and drop it over another, it will push the label beneath the dragged label to the side, so they will never overlap one another.
I've seen how collision is detected in the colliding mice example, where it uses a QGraphicsScene to draw the QGraphicsItem mice on, and scene()->collidingItems(this) to see which mice are colliding.
The problem is that the fridge magnets example uses a class that inherits QWidget in place of QGraphicsScene, so there's no collidingItems() method to check when we have a collision.
How do I go about doing that?
| You can get the location and size of each QWidget from geometry(), which returns a QRect. QRect has function intersects(), which will tell you if it intersects another QRect. After the drop is complete, iterate through all of the labels and check if any of them do intersect the new position.
(This will be easier if you modify dragwidget to keep a QList<DragLabel*> of each label on the dragwidget.)
QRect droppedRect = newLabel->geometry();
foreach(DragLabel* label, dragLabelList)
{
if (droppedRect.intersects(label->geometry())
{
// Add to the list of covered labels that need to be moved.
}
}
The harder part: If there is an intersection, move the old label out of the way.
Maybe try the following algorithm: Move the offending label out of the way in the direction that takes the least movement. Now check it against all the other labels. Any of those that are covered should be moved in the same direction. Repeat until all the labels are uncovered.
|
2,328,666 | 2,328,726 | vim plugin comment blocks | I looked around, but didn't find what I wanted. I need a vim plugin to insert blocks of code and prompt me for values in the comment.
// ********************** BeWee ************************
// *** Creation Date:
// *** Last Modification Date:
// *** File name: BeWee.cpp
// *********************************************************
// *** Programmer: Name
// *** Email: Email
// *********************************************************
// *** This file contains the implementation for the class
// *** BeWee. The class BeWee models ...
// ***
// *********************************************************
I want to be prompted to enter the BeWee, Creation Data, etc
I currently have these comments in a file and just read them into the vim editor.
TIA
| Look at SnipMate. Follow the install guide and make a snippet with the layout.
|
2,328,671 | 2,328,715 | constant variables not working in header | if I define my constant varibles in my header like this...
extern const double PI = 3.1415926535;
extern const double PI_under_180 = 180.0f / PI;
extern const double PI_over_180 = PI/180.0f;
I get the following error
1>MyDirectX.obj : error LNK2005: "double const PI" (?PI@@3NB) already defined in main.obj
1>MyDirectX.obj : error LNK2005: "double const PI_under_180" (?PI_under_180@@3NB) already defined in main.obj
1>MyDirectX.obj : error LNK2005: "double const PI_over_180" (?PI_over_180@@3NB) already defined in main.obj
1>MyGame.obj : error LNK2005: "double const PI" (?PI@@3NB) already defined in main.obj
1>MyGame.obj : error LNK2005: "double const PI_under_180" (?PI_under_180@@3NB) already defined in main.obj
1>MyGame.obj : error LNK2005: "double const PI_over_180" (?PI_over_180@@3NB) already defined in main.obj
but If I remove those constants from the header and put them in the document that is including the header like this...
const double PI = 3.1415926535;
const double PI_under_180 = 180.0f / PI;
const double PI_over_180 = PI/180.0f;
It works
Does anyone have Idea what I might be doing wrong ??
Thanks
| The problem is that you define objects with external linkage in header file. Expectedly, once you include that header file into multiple translation units, you'll get multiple definitions of the same object with external linkage, which is an error.
The proper way to do it depends on your intent.
You can put your definitions into the header file, but make sure that they have internal linkage.
In C that would require an explicit static
static const double PI = 3.1415926535;
static const double PI_under_180 = 180.0f / PI;
static const double PI_over_180 = PI/180.0f;
In C++ static is optional (because in C++ const objects have internal linkage by default)
const double PI = 3.1415926535;
const double PI_under_180 = 180.0f / PI;
const double PI_over_180 = PI/180.0f;
Or you can put mere non-defining declarations into the header file and put the definitions into one (and only one) implementation file
The declarations in the header file must include an explicit extern and no initializer
extern const double PI;
extern const double PI_under_180;
extern const double PI_over_180;
and definitions in one implementation file should look as follows
const double PI = 3.1415926535;
const double PI_under_180 = 180.0f / PI;
const double PI_over_180 = PI/180.0f;
(explicit extern in the definitions is optional, if the above declarations precede the definitions in the same translation unit).
Which method you will choose depends on your intent.
The first method makes it easier for the compiler to optimize the code, since it can see the actual value of the constant in each translation unit. But at the same time conceptually you get separate, independent constant objects in every translation unit. For example, &PI will evaluate to a different address in each translation unit.
The second method creates truly global constants, i.e. unique constant objects that are shared by the entire program. For example, &PI will evaluate to the same address in each translation unit. But in this case the compiler can only see the actual values in one and only one translation unit, which might impede optimizations.
Starting from C++17 you get the third option, which sort of combines "the best of both worlds": inline variables. Inline variables can be safely defined in header files despite having external linkage
inline extern const double PI = 3.1415926535;
inline extern const double PI_under_180 = 180.0f / PI;
inline extern const double PI_over_180 = PI/180.0f;
In this case you get a named constant object whose initializer value is visible in all translation units. And at the same time the object has external linkage, i.e. it has a global address identity (&PI is the same in all translation units).
Granted, something like that might only be necessary for some exotic purposes (most use cases in C++ call for the first variant), but the feature is there.
|
2,328,732 | 2,328,760 | Pass variable "name" in C++ | I currently use the following template simply as a way to check for NULL pointer and if NULL then print out an error message to a log file and then return false.
template< typename T >
static bool isnull(T * t, std::string name = "")
{
_ASSERTE( t != 0 );
if( !t )
{
if( !(name.length()) ) name = "pointer";
PANTHEIOS_TRACE_ERROR(name + " is NULL");
return false;
}
return true;
}
I currently call this as follows:
if( !(isnull(dim, BOOST_STRINGIZE(dim))) ) return false;
If you notice I need to pass in the "name" of the pointer-variable that I want to print to the log file, as the 2nd parameter. I am currently using BOOST_STRINGIZE that simply converts any text inside the parentheses to a string.
The following are the disadvantages of my template implementation (for my usage at least)
Anyone could pass in anything as parameter to BOOST_STRINGIZE to print out in log file - since the 2 parameters are not related in anyway - so I would not necessarily see the "variable name" that is actually NULL
We have to remember to pass in the 2nd parameter, else useless.
Is there anyway I can have the "name" of that 1st variable be automatically determined, so that I can omit passing it in, as the 2nd parameter, with every call?
| You could put it all in one macro:
#define IS_NULL(name_) isnull(name_, #name_)
Note that BOOST_STRINGIZE expands its argument if its a macro, which may or may not be what you want:
#define X(x_) std::cout << BOOST_STRINGIZE(x_) << " = " << x_ << std::endl;
X(NULL); // prints: "0 = 0"
|
2,328,960 | 2,328,970 | C++ constructors fun - constructing Foo with a copy of itself | I have:
class Foo;
class Bar {
Foo foo;
Bar(): foo(foo) {};
}
Bar bar;
At this point, is
bar.foo // <--- how is this initialized?
[This question arose from a buggy ref-counted pointer implemntation; I could have sworn that I ensured each pointer was pointing at something non-null; but I ended up with a pointer that pointed at something NULL.]
| foo is fully initialized once you've entered the body of the constructor (that's the guaranteed general case; specifically once it has finished initializing in the initialize list.)
In your case, you are copy-constructing from a non-constructed object. This results in undefined behavior, per §12.7/1 (thank you, gf):
For an object of non-POD class type (clause 9), before the constructor begins execution and after the destructor finishes execution, referring to any nonstatic member or base class of the object results in undefined behavior.
In fact, it gives this example:
struct W { int j; };
struct X : public virtual W { };
struct Y {
int *p;
X x;
Y() : p(&x.j) // undefined, x is not yet constructed
{ }
};
Note, the compiler is not required to give a diagnosis of undefined behavior, per §1.4/1. While I think we all agree it would be nice, it simply isn't something the compiler implementers need to worry about.
Charles points out a loophole of sorts. If Bar has static storage and if Foo is a POD type, then it will be initialized when this code runs. Static-stored variables are zero-initialized before an other initialization runs.
This means whatever Foo is, as long as it doesn't need a constructor to be run to be initialized (i.e., be POD) it's members will be zero-initialized. Essentially, you'll be copying a zero-initialized object.
In general though, such code is to be avoided. :)
|
2,328,975 | 2,329,080 | How to modify properties of Bitmaps in C++ | Bitmap bmp(100,100, PixelFormat32bppARGB);
bmp.SetPixel(2,2,Gdiplus::Color::AliceBlue);
int x = bmp.GetHeight();
int y = bmp.GetWidth();
Gdiplus::Color* ccc = new Gdiplus::Color;
Gdiplus::Color* ccc2 = new Gdiplus::Color;
bmp.GetPixel(2,2,ccc);
bmp.GetPixel(0,0,ccc2);
In the past sample code, the bitmap properties are always appearing as if it's null. height and width are always zero and color of any pixel is always the same. What is the right way to modify properties of the bitmap?
| The constructor you're calling doesn't fill in the pixel data of your bitmap. You need to call a version of bmp.FromX() after construction to fill your bitmap.
Alternately, you can call another constructor that gives you a filled bitmap.
Also, you may want to wrap your SetPixel() call with calls to LockBits() and UnlockBits().
Read up on the spec here for more details.
|
2,329,175 | 2,335,088 | MySQL, C++: Need Blob size to read blob data | How do I get the size of data in a BLOB field in the Result Set? (Using C++ and MySQL Connector C++)
In order to read the data from the result set, I have allocate memory for it first. In order to allocate memory, I need to know the size of the blob data in the result set.
Searching the web and StackOverflow, I have found two methods: OCTECT and BLOB stream.
One method to find the BLOB size is to use OCTECT() function, which requires a new query and produces a new result set. I would rather not use this method.
Another method is to use the blob stream and seek to the end, and get the file position. However, I don't know if the stream can be rewound to the beginning in order to read the data. This method requires an additional read of the entire stream.
The ResultSet and ResultSetMetaData interfaces of MySQL Connector C++ 1.0.5 do not provide a method for obtaining the size of the data in a field (column).
Is there a process for obtaining the size of the data in a BLOB field given only the result set and a field name?
I am using MySQL Connector C++ 1.0.5, C++, Visual Studio 2008, Windows Vista / XP and "Server version: 5.1.41-community MySQL Community Server (GPL)".
| You could do a select like:
select LENGTH(content),content where id=123;
where content is the BLOB field.
Regards.
see: LENGTH(str)
|
2,329,294 | 2,329,308 | Segmentation fault when using stream extraction into a char pointer | I have a question. I have the following struct:
typedef struct{
int vin;
char* make;
char* model;
int year;
double fee;
}car;
Then I have the following method that asks the user for the make of a car and returns it as a char pointer:
char* askMake(){
char* tempMake = NULL;
cout << "Enter Make:" << endl;
cin >> tempMake;
return tempMake;
}
Then I have a temp car struct:
car tempCar;
And I am trying to assign a value to it this way:
tempCar.make = askMake();
It compiles fine, but I get a segmentation fault at runtime.
| You have to allocate memory for tempMake.
Try this:
char* askMake(){
char* tempMake = new char[1024]; //Arbitrary size
cout << "Enter Make:" << endl;
cin >> tempMake;
return tempMake;
}
Don't forget to free with delete[] the memory that you allocated.
If you don't want memory leaks, you can avoid this using smart pointers like boost::shared_ptr or boost::scoped_ptr or similar. You can see more about this here.
|
2,329,461 | 2,329,765 | Can't add strings in C++ | #include <iostream>
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message;
return 0;
}
Why does this code not work? Error returned:
error: invalid operands of types `const char[6]' and `const char[8]' to binary `operator+'
Thanks in advance!
EDIT:
Thanks for all the answers. This is my first time on the site and I am astonished at the number of elaborate explanations in such a short time interval.
Regarding the actual question. How come this works then:
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
Is it because ", world" and afterwards "!" get concatenated with variable hello (which is defined)?
| Because in C++, string literals (like "Hello" are not of type std::string. They are plain char arrays, or C-style strings.
So for the line const std::string message = "Hello" + ", world" + exclam;,the types the compiler has to work with are:
const std::string message = const char[6] + const char[8] + std::string;
and given the associativity of +, the operations it has to perform are:
const std::string message = ((const char[6] + const char[8]) + std::string);
That is, the left-most addition must be evaluated first, and the result passed to the rightmost addition.
So the compiler tries to evaluate const char[6] + const char[8].
There is no addition defined for arrays. Arrays are implicitly converted to pointers, but this doesn't help the compiler. That just means it ends up with const char* + const char*, and no addition is defined for pointers either.
At this point, it doesn't know that you want the result to be converted to a std::string.
However, in your second example:
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
it works, because the operations the compiler would see were std::string + const char[8] + const char[2]. Here, the first addition can be converted to std::string + const char*, and here the addition operator is defined, and returns a std::string. So the compiler has successfully figured out the first addition, and since the result was a string, the second addition looks like this: std::string + const char[2], and like before, this isn't possible, but the array can be converted to a pointer, and then the compiler is able to find an addition operator that works, again resulting in a std::string.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.