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 |
|---|---|---|---|---|
6,749,617 | 7,252,636 | How to use a C++ member function as the callback function for a C framework | There is a C library (which I cannot change) that supports a callback function of the type
void (*callback)(void *appContext, int eventid)
I want to set a C++ function as the callback.
Specifically I have following questions?
Do I need to declare the callback function under "extern C" block?
Does a member function ... | Does callback function need to be declared under extern "C"?
NO. extern "C" is necessary only when you are calling a C++ function directly, without the use of function pointers, from C. If function pointers are used, extern "C" is not required.
Can I use non-static member functions as a callback?
NO. Non-static member... |
6,749,983 | 6,750,029 | Operator overloading ( & -> )in C++ | I have some basic questions on operator overloading in C++.
I am reading "Thinking in C++, volume 1" and it says that operators that can't be overloaded are member selection operator . , member dereference operator * . So it looks like other operators can be overloaded
Can I overload & operator? But won't this conf... | overloading an operator is the same as overloading any other function. The compiler knows what to use based on the parameters you specified. So, no, the compiler won't get confused. You on the other hand, may get confused. This is one of the reasons why a lot of programmers say to avoid overloading operators (I dis... |
6,750,129 | 6,750,211 | Pointer arithmetic on auto_ptr in C++ | I am reading the implementation of auto_ptr in C++ STL.
I see that commonly needed operations on pointers like -> and * are overloaded so that they retain the same meaning. However, will pointer arithmetic work on auto pointers?
Say I have an array of auto pointers and I want to be able to do something like array + 1 a... | An auto_ptr can only point to a single element, because it uses delete (and not delete[]) to delete its pointer.
So there is no use for pointer arithmetic here.
If you need an array of objects, the usual advice is to use a std::vector instead.
|
6,750,424 | 6,751,578 | Visual studio 2008 "Debug Assertion Failed" message while calling QDomElement::text() function | I have included the source, the error and the stack trace. How do I resolve this issue? I need pointers(explanation) on how to proceed regarding this
Source Code :
QFile xmlInputFile(".\\gatewayipmonitor.xml");
xmlInputFile.open(QIODevice::ReadOnly);
QByteArray xmlData(xmlInputFile.readAll());
QDomDocument doc;
do... | I was running the program in the release build but linking against debug build libraries(Qtcored.lib). That was the issue.
|
6,750,549 | 14,731,272 | How to make MinGW to treat texts like "text" as const char* | AFAIK, after upgrading to MinGW 4.4.* some time ago all of my literally written strings (like "i'm the string") are treated as of the type std::string. Is there any command line option to make MinGW treat them as const char* as it was before?
| Strings are per default char * / char[] in C / C++, only if you explicit say its a std::string you'll get those.
Example:
std::cout << "first:\t" << typeid("aa").name() << std::endl;
std::cout << "second:\t" << typeid(std::string("a")).name() << std::endl;
Output:
first: A3_c
second: Ss
Result:
first: a char array... |
6,750,815 | 7,509,497 | How to turn off Glibc run-time protections? | I am trying to learn about code vulnerabilities, and am testing some simple programs I wrote. However, many of the issues Glibc catches during runtime (e.g. Stack-Smashing, Double Free, etc.). Thus I would like to be able to run my programs without Glibc's runtime detection errors. Is there a way to turn off Glibc's... | Check the man page for malloc(3) for usage of the MALLOC_CHECK_ environment variable. Using this, you can turn off 'aborts' for those double free errors and whatnot to play with things.
man malloc
So if your program was called 'badfree', you can either set MALLOC_CHECK_ (note trailing underscore) with an export comma... |
6,751,061 | 6,753,817 | When is using 'typeid' the best solution? | There are many reasons not to use typeid. Other than for using members of type_info (implementation defined behavior), it is usually (always?) possible to provide similar functionality using other C++ language features, eg: overloading, virtual functions etc.
So, excluding usage that relies on the implementation defin... | boost::any uses typeid to implement any_cast.
template<typename T> any_cast(const any& other) {
if(typeid(T) != other.type()) throw bad_any_cast();
//...actual cast here...
}
You can't be sure T is polymorphic, so dynamic_cast is out of the question, and the enclosed type within the boost::any call is lost by... |
6,751,716 | 6,751,762 | how to implement timer with interval in C++ | I am writing a program in C++ where I need to call a function in every 250 ms. It is really easy in C#, but i don't have much idea how to implement that in C++.
I would really appreciate if anyone could suggest me the solution.
| The SetTimer function is used to create a Windows timer.
|
6,751,749 | 6,751,809 | What is the size of a pointer? | Is the size of a pointer the same as the size as the type it's pointing to, or do pointers always have a fixed size? For example...
int x = 10;
int * xPtr = &x;
char y = 'a';
char * yPtr = &y;
std::cout << sizeof(x) << "\n";
std::cout << sizeof(xPtr) << "\n";
std::cout << sizeof(y) << "\n";
std::cout << sizeof(yPtr) ... | Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern deskto... |
6,751,779 | 6,751,906 | C++ pointer assignment statement doesn't seem to work / do anything | I have the following method in a template class (a simple FIFO queue) and while GDB debugging, I found that the statement to reassign the pointer 'previous' to 'current' seems to do nothing.
previous starts as NULL and current is not NULL when this statement is executed, yet previous remains as NULL.
Has anyone seen an... | Where are you inspecting the value of previous? If you're doing it within this function, after the assignment, then make sure the build has optimizations turned off, and then try it again.
On the other hand, if you're watching previous outside the scope of this function, then it'll never get modified. When you call sea... |
6,751,836 | 6,779,373 | storing vertex depth information in a texture in opengl shadow mapping | I'm currently programming shadow mapping (cascaded shadow mapping, to be precise) into my c++ opengl engine. I therefore want to have a texture containing the distance between my light source and every pixel in my shadow map. Which texture type should I use?
I saw that there is a GL_DEPTH_COMPONENT texture internal fo... | I'm not sure what you mean with invert (I'm sure you cannot mean to invert the distance as this won't work). What you do is transform the distance to the light source into the [0,1] range.
This can be done by constructing a usual projection matrix for the light source's view and applying this to the vertices in the sha... |
6,751,850 | 6,751,895 | Explicit Assignment vs Implicit Assignment | I'm reading a tutorial for C++ but it didn't actually give me a difference (besides syntax) between the two. Here is a quote from the tutorial.
You can also assign values to your variables upon declaration. When we
assign values to a variable using the assignment operator (equals
sign), it’s called an explicit as... | The first is preferred with primitive types like int; the second with types that have a constructor, because it makes the constructor call explicit.
E.g., if you've defined a class Foo that can be constructed from a single int, then
Foo x(5);
is preferred over
Foo x = 5;
(You need the former syntax anyway when more t... |
6,752,560 | 6,753,397 | Is there something for function composition in <functional>? | What I want to do is done pretty easily with C++0x lambdas. I just want to figure out how to do it with bind1st and bind2nd only.
I need to find the first element i in the vector v, such that (i-1)/p1 == p2 where p1 and p2 are predefined integers.
find_if(v.begin(), v.end(), ???)
I can't figure out how to form the pre... | Unfortunately, what you're trying to do is not possible with only the current functional library. You would need to create your own class or function to do the composition.
Boost used to offer a Compose library that was used to compose functions like this, but I think it was removed when Bind and Lambda were introduced... |
6,752,567 | 6,752,688 | Casting a large number type to a smaller type | I've had a good look around and can't find a similar question so apologies if it has been asked before.
I'm just playing around with types and numbers and I am wondering if the following behaviour can be guaranteed.
If I declare 2 variables as
unsigned char BIT_8 = 0;
unsigned short int BIT_16 = 0xFF01;
and then do t... |
Is it guaranteed that if I cast a 16 bit type to an 8 bit type that the leading byte will be lost?
Depends on whether you are working with signed or unsigned types (see section 4.7 §2 and §3):
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modu... |
6,752,745 | 6,753,987 | C++ template function with pointer argument taken from iterator gives error | I am sorry if the title was not descriptive enough, I have no idea what is wrong with this:
template <class S, class P>
P* findPolicy(boost::ptr_vector<P> &policies,S *state)
{
typename boost::ptr_vector<P>::iterator it;
for ( it = policies.begin(); it != policies.end(); ++it)
{
if ( *it->getSt... | It can't deduce the template argument for S and P however since you explicitly call the method with arguments you're skipping deduction and so the compiler is simply telling you it can't find that specific match.
The most likely reason it can't find it is because either S or P are templates and not actual types. If so ... |
6,752,880 | 6,753,051 | How to "upgrade" mutex ownership from shared to upgrade? | Sorry for my dumb question, but how can I
upgrade shared ownership to upgrade?
So what method is the opposite of the unlock_upgrade_and_lock_shared() one?
(Is there any.)
So if an ownership is shared how can i "upgrade" it to upgrade without unlock_shared() and lock_upgrade()?
And I can not understand the concept of h... | Either your thread has upgrade ownership, or it has shared ownership, or it has exclusive ownership. lock_upgrade() converts your ownership from shared to upgrade. Upgrade ownership is provided so you have a direct way to obtain exclusive ownership without releasing the shared lock.
The docs here might prove instruc... |
6,753,511 | 6,753,715 | Wrapping message constants in namespace | I have a series of constant strings that correspond to message IDs; I'm trying to create a centralized place for these constants as they are used in various classes in my application. I was originally going to create a namespace containing them:
// MessageIDs.hh
namespace MessageIDs {
const std::string kMessage1("Mes... | 1) I see one definite advantage of this approach: you always see the value of the defined constant in the right place. I.e. should the constants be defined extern, you would have to place the definitions in one cpp-file along with the initializers, and leave the header with extern const without the value, which would m... |
6,753,521 | 6,753,570 | Linker error when trying to add constant to iterator | #include <string>
#include <iostream>
using namespace std;
struct foo {
static const int X = 3;
static char bar(const string &str) {
// return str[X]; // this works
return *(str.begin() + X); // this fails
}
};
int main() {
cout << foo::bar("abcdefg") << endl;
}
When compiling this, I... | You need to define foo::X in addition to declaring it. Do it outside of foo.
const int foo::X;
|
6,753,679 | 6,753,709 | Pure virtual functions and unused arguments in child functions in C++ | I have the following:
class Parent {
public:
virtual bool foo(vector<string> arg1, vector<string> arg2) = 0;
};
class Child : public Parent {
public:
bool foo(vector<string> arg1, vector<string> arg2);
};
// arg1 and arg2 not used - GIVES WARNING
bool Child::foo(vector<string> arg1, vector<string> arg2) {
... | Don't specify the parameter names:
// arg1 and arg2 not used - GIVES WARNING
bool Child::foo(vector<string>, vector<string>) {
return false;
}
That should solve the warnings.
If your compiler for whatever reason doesn't support it - do this:
// arg1 and arg2 not used - GIVES WARNING
bool Child::foo(vector<string> ... |
6,753,782 | 6,820,625 | Edit Value of a QDomElement? | I need to edit the text of a QDomElement - Eg
I have an XML file with its content as -
<root>
<firstchild>Edit text here</firstchild>
</root>
How do I edit the text of the child element <firstchild>?
I don't see any functions in the QDomElement of QDomDocument classes descriptions provided in Qt 4.7
Edit1 - I ... | This will do what you want (the code you posted will stay as is):
// Get element in question
QDomElement root = doc.documentElement();
QDomElement nodeTag = root.firstChildElement("firstchild");
// create a new node with a QDomText child
QDomElement newNodeTag = doc.createElement(QString("firstchild"));
QDomText newN... |
6,753,788 | 6,764,696 | Getting PyUblas sample working in Ubuntu | I would like to call C++ functions in python which return uBLAS vector/matrices.
There is a package to do this called PyUblas,
but am having trouble getting this to work in Ubuntu.
Can anyone walk me through the steps to get this sample to work?
Also, I am somewhat confused with the installation instructions. I did not... | I guess that wasn't so hard. Here's what I did to run the small sample on the website and in test/samply.py.
After downloading and unpacking PyUblas, and having the necessary libraries installed, cd into PyUblas-VERSION
./configure.py --help
./configure.py --some-options
sudo python setup.py install
cd test/
g++ -I/usr... |
6,753,795 | 6,753,830 | Finding origin of Pointer | If you have an object1 and a pointer pointing to the object2, and we are currently in Object 2, then can we get from object2 to object1? How?
(OBJECT1) --------> (OBJECT2)
we are here and we don't know where/what OBJECT1 is
| No. Suppose you have several pointers pointing to OBJECT2
(POINTER1) ------------\
(POINTER2) -------------\
(POINTER3) --------------> (OBJECT2)
..... -------------/
(POINTERN) ------------/
When you "go up", to which pointer should you go?
|
6,754,049 | 6,754,283 | Setting parent for a QMessageBox | i can't understand what's the benefit of setting parent for a QMessageBox, for instance in the following code:
void mainWindow::showMessage(QString msg) {
QMesageBox::information(this, "title", msg); //'this' is parent
}
can somebody help me ?
| Probably a few things. First of all QMessageBox inherits from QDialog. Since QDialog has a concept of a parent, QMessageBox should too for consistency.
Specifically, the documentation says:
parent is passed to the QDialog constructor.
At the very least, a new dialog is often displayed centered in top of its parent.
H... |
6,754,081 | 6,754,216 | C++, COM and passing strings | I am debugging some other programmer's source code of a Windows Media Player plugin. This plugin causes WMP to crash sometimes, and sometimes it takes really long time to open plugin settings window. The problem occurs only when opening settings window while music is being played back. It opens without issues if the pl... | Put simply, COM doesn't know how to pass around pointers of type unsigned char *. The default marshalling rules are applied (since the interface definition doesn't specify any parameter attributes), and, if I'm interpreting this correctly, COM marshals the outer pointer itself txt properly, but treats *txt as a pointer... |
6,754,126 | 6,754,187 | MSVC vs GCC: variable declaration in function | As everybody knows, C standard require to declare variables at the top of function body.
C++ allows to declare it anywhere, just before it will be used.
MSVC follow standard when work with .c and .cpp source files.
GCC allows to declare variables anywhere in function body even if source file is .c
I have a huge number ... | C89 standard required that. Current C99 one doesn't. Anyway, the switch is /TP to treat all the input files as C++ and /Tp<file> to treat a select one — keep in mind that this might not fix anything, but also introduce new errors and it will mangle the names, so interop might be hurt.
The best solution would be to simp... |
6,754,241 | 6,787,070 | GUI-Toolkit that supports propely OpenGL3 | I am in need of a GUI-Toolkit that properly supports OpenGL3 and allow creating of a forward compatible profile.
Normally I use wxWidgets. But when I try to create the context I use in my engine on a wxWindow or wxPanel, GetDC() fails because the Window lacks CS_OWNDC.
I really don't want to learn QT, but it does not ... | Qt supports forward compatible contexts in versions 4.7 and above:
http://doc.qt.nokia.com/4.7/qglformat.html
|
6,754,270 | 6,754,377 | Seg Fault on getaddrinfo() | I am getting a segmentation fault on my getaddrinfo call and cannot figure out why. It happens on both my server and client. Some code (server side) is -
class TcpServer {
public:
TcpServer(int);
~TcpServer();
void launchServer();
void communicate();
private:
const char* port;
int fd;
in... | getaddrinfo("127.0.0.1", port, &hints, &servinfo)
^
That should be a char *. I am guessing you are passing an integer and forcing the library to access an invalid address.
EDIT
In light of the comment of Blagovest Buyukliev I believe you are doing something like this in the constructor: this-... |
6,754,278 | 6,765,123 | Qt C++ QMenuBar in Layout problem when scrolling | I am new to Qt and am having difficulties with scrollbars in QWidgets.
I have a layout in a widget and the layout contains a QMenuBar. The Scroll area is associated with the widget. The scroll works fine but when the user scrolls down the Menubar goes out of sight. Is there any way to keep the Menu at the top?
Any help... | Figured out the solution to the problem.
Created a QMainWindow which contains the menu bar. Added a QWidget which contains the layout. The scroll area is associated to the QWidget. The central widget of the mainwindow is set to be the scroll area.
main->setLayout(layout);
this->setCentralWidget(scrollArea);
scrollArea-... |
6,754,434 | 6,754,949 | How can I use boost asio sockets for full duplex streaming efficiently? | I'm writing a performance-critical bidirectional streaming server using boost.asio.
The server works this way :
Thread A treats and pushes objects to be sent in the OUTPUT queue
Thread B waits for objects in the INPUT queue to treat them
Thread C is an acceptor thread that accepts incoming clients and creates a CLIE... |
The standard async approach fails here (the send callbacks may block
other callbacks while waiting for a new object to send)
The async model should work fine, and if used properly is definitely going to scale better—it only falls apart when you introduce blocking. Instead of ditching async, here's what I would sug... |
6,754,454 | 6,754,495 | Speed difference between If-Else and Ternary operator in C...? | So at the suggestion of a colleague, I just tested the speed difference between the ternary operator and the equivalent If-Else block... and it seems that the ternary operator yields code that is between 1x and 2x faster than If-Else. My code is:
gettimeofday(&tv3, 0);
for(i = 0; i < N; i++)
{
a = i & 1;
... | There's a good chance that the ternary operator gets compiled into a cmov while the if/else results in a cmp+jmp. Just take a look at the assembly (using -S) to be sure. With optimizations enabled, it won't matter any more anyway, as any good compiler should produce the same code in both cases.
|
6,754,538 | 6,754,588 | Can an inner class of a template class be a non-template class? | I am making a template class with an inner utility class. All specializations of the template want the same inner class:
template<...> class Outer {
class Inner { };
};
That gives me Outer<...>::Inner but I want all Inner to be the same type, as if I'd just written:
class Inner { };
template <...> class Outer { }... | The nested class can be a non-template, but every instantiation of the template will have its own nested class because they're (otherwise) unrelated types. You can do
namespace detail {
class Inner {};
} // detail
template<...>
class Outer {
typedef detail::Inner Inner;
};
|
6,754,924 | 6,754,980 | When to Start Learning C++ | I've been coding in Java and C# for about 4-5 months now. Great languages, but I feel like I'm really ready to take the next step. I'm anxious to begin learning c++, and I've already started to do so, but I'm admittedly having a hard time with it. It really does take a lot more effort to learn and accomplish anything w... | IMHO, the best way to learn a new language is with a "pet project".
You will make mistakes, your code will be a mess, and you will look back at your mess and realize that you should throw the whole thing away. BUT, you were excited with every incremental feature, and you enjoyed the "pet project" to the point where yo... |
6,755,111 | 6,755,132 | read input files, fastest way possible? | I have numerous text files of data in the form of float numbers. I'm looking for the fastest way to read them in C++. I can change the file to binary if that's the fastest.
It would be great if you could give me hint or refer me to a website with complete explanation. I don't know whether there is any library that doe... | Having a binary file is the fastest option. Not only you can read it directly in an array with a raw istream::read in a single operation (which is very fast), but you can even map the file in memory if your OS supports it; you can use open/mmap on POSIX systems, CreateFile/CreateFileMapping/MapViewOfFile on Windows, or... |
6,755,250 | 6,755,312 | Format output in a table, C++ | How can I output data to the console in a table in C++? There's a question for this in C#, but I need it in C++.
This, except in C++: How To: Best way to draw table in console app (C#)
| Can't you do something very similar to the C# example of:
String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);
Like:
printf("|%5s|%5s|%5s|%5s|", arg0, arg1, arg2, arg3);
Here's a reference I used to make this: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
|
6,755,271 | 6,755,558 | How do I monitor and synchronize a collection of files? | Hi I'm trying to create a simple music library for my application that uses sqlite to store information about the files. I want to know how to update my database when the files making up the library change.
One way I thought of figuring out whether or not I need to update the db is to count the number of files that ma... | You can use several techniques.
Scan all directories added by the user to see if the last modified timestamp has changed. If it has rescan the file. You can run this in a separate thread at a low priority if you like.
When a user clicks on the audio track in the UI rescan the file. If it doesn't exist alert the user a... |
6,755,375 | 6,760,159 | Where to store Qt imports for OSX deployment? | I’m making my QT-application ready for shipping.
I’ve got one import -> QtDesktop.
I put it under Contents/imports (the dylib is under Contents/imports/QtDesktop/plugin).
Then I fixed its dependencies with install_name_tool -id & -change.
Upon starting the application it keeps saying “module “QtDesktop” is not installe... | Check out this excellent link from Nokias Qt Documentation. They describe the steps you mention with install_name_tool. But they recommend putting plugins in a sligtly diffrent folder.
Plugins can be put in the Contents/PlugIns section of a bundle. An
advantage of using this location is that the plugins will show up... |
6,755,483 | 6,756,689 | Call of a wrapped static c++ library in an objc library causes linker error | I have a cpp static library and tried to wrap this in a static obj-c library so that it looks from the outside like a normal obj-c lib.
My obj-c lib compiles fine, but when i try to use this lib in an App I get the following Linker error:
Apple Mach-O Linker (Id) Error
Undefined symbols for architecture i386:
"operat... | I'm not familiar with your compiler or project but it sounds like the standard library isn't being linked. Does a -lstdc++ option fix anything?
|
6,755,491 | 6,756,807 | Function calls seen before _start and main in backtrace | I received a backtrace of my program (qt app running on RHEL 5.3) from a coworker and as I was analyzing it I found something I could not explain. If you look at this backtrace, you will notice the trace for main and _start. But before that we see _ZN19datalog_render_area9prepStripEh and _ZN12QMutexLockerD1Ev which ... | Most likely, you're seeing garbage on the stack. In order to get an accurate stack trace, the debugger needs either frame pointers (often omitted on x86 to save a register) or debug information. Without this information, it tries to guess - it scans through the stack for pointers that look sorta-kinda-like code address... |
6,755,569 | 6,755,685 | How do header and implementation files work in C++? | I have a question about the relationship between header and implementation files in C++.
I have received two empty header files and one empty implementation file. When I say "empty" I mean that the files only contain method declarations; I have to implement the code inside each method. (I thought that posting the code ... | 1) You need an interface only if it is likely that the implementation will change later on. That will leave you free to make all the changes you want to the internals of your code without impacting the people using it to create software. That means that the users should only see the interface class and never the implem... |
6,755,604 | 6,755,641 | "invalid conversion from" with pthread_create issue | Any comment is appreciated for the compile error below.
Although my question is similar to other thread: pthread function from a class, I still haven't been able to solve my problem. I am still not that familliar with pointer, and thread programming in C & C++.
Error
../src/Main.cpp: In function ‘int main(int, char**)’... | Your ThreadEntryPoint must return void*.
The error indicates the type that is expected, and that is the function pointer type that you are required to use.
|
6,755,636 | 6,755,820 | How to get displayed width of a string? | When you have non-fixed width characters (such as \t) in a string , or escape codes, such as those for ANSI color (such as \1xb[31m), these characters add to the .length() of an std::string, but do not add to the displayed length when printed.
Is there any way in C++ to get the displayed width of a string in *nix?
For ... | Most commonly, a tab asks the terminal program to move the cursor to a column that's a multiple of 8, though many terminal programs let you configure that. With such behaviour, how much width a tab actually adds depends on where the cursor was beforehand relative to the tab stops. So, simply knowing the string conten... |
6,755,652 | 6,755,722 | Problems using string::find_first_not_of and string::find_last_not_of | I know this problem crops up a lot, but I couldn't find a piece of code which worked for me.
I am trying to strip all punctuation off of an incoming string using find_first_not_of and find_last_not_of methods in the string library:
//
//strip punctuation characters from string
//
void stripPunctuation(string &temp)
{
... | Never pass .end(). It points to an invalid iterator, which represents the end.
If you want to delete the last character in a string, use temp.erase(temp.length()-1).
If I understand you correctly.
edit:
it seems erase() only accepts an iterator, which is what i thought initially.
That is not true:
string& erase ( si... |
6,755,673 | 6,755,760 | C++ Conversion operator for converting to function pointer | I'm been grinding my head against an idea that is simple enough in my head, but I can't figure out how to implement in C++.
Normally, I can declare a class with a conversion operator like in this simple example:
class Foo
{
private:
int _i;
public:
Foo( int i ) : _i(i) { }
operator int( ) const
{
... | Since you must know:
(*operator int() const)(int, int)
{
return _funcPtr;
}
(Fixed. Again.)
Update: I've been informed by Johannes Schraub and Luc Danton that this syntax is in fact not valid, and that you really must use a typedef. Since you say that typedefs aren't an option, here's a helper class that can wrap y... |
6,755,761 | 6,755,951 | Getting value of C++ list iterator problem | I have code like this:
struct sWindowInfo {
WNDPROC pPrevWndProc;
};
typedef std::list<sWindowInfo> windowsList;
And function, which returns pointer to iterator of first window-info struct in list:
windowsList::const_iterator* windowGet();
Code like this works fine:
if (windowsList::const_iterator* itr = windowGe... | Both implementations are wrong. You should not return pointers to iterator since it will be invalid after windowGet() call.
It is the same thing as doing this:
int* getInt()
{
int a = 10;
return &a;
}
int* a = getInt();
int v = *a ; // v may be 10 or may be not
You may ask why first code is working? It is... |
6,755,991 | 6,756,040 | catching std::exception by reference? | I have a silly question. I read this article about std::exception http://www.cplusplus.com/doc/tutorial/exceptions/
On catch (exception& e), it says:
We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception,... | The reason for using & with exceptions is not so much polymorphism as avoiding slicing. If you were to not use &, C++ would attempt to copy the thrown exception into a newly created std::exception, potentially losing information in the process. Example:
#include <stdexcept>
#include <iostream>
class my_exception : pub... |
6,756,059 | 6,756,197 | C++ using C code using double underscores in defines and identifiers | I understand that in C++ double underscores in identifiers are reserved for the compiler. I have some C code which has characteristics similar to this in the corresponding header files:
extern "C" {
#define HELLO__THERE 1
int hello__out__there( int );
}
I will be using this header in a C++ project, and plan to... |
double underlines in identifiers are reserved for the compiler
First, it's underscore I guess. Second such identifiers are reserved. That doesn't hold one back to not use it. You can use it (until there is no naming conflict).
Is this acceptable behavior in C++, covered by the standard?
Yes. It's acceptable. Howeve... |
6,756,091 | 6,756,118 | How to produce an NSString with format HxHHHHHHHH representing a float value in Objective C, C++, or C? | Suppose we have
float x = 24.0;
I want to do the following:
// hexRepresentation is of format HxHHHHHHHH
// where H is a hexadecimal symbol 0-9 or a-f
NSString *hexRepresentation = [self hexadecimalFromFloat:x];
Please help me complete the following method:
- (NSString *)hexadecimalFromFloat:(float)flt {
NSStrin... | Rough, untested code:
unsigned int *fp = (unsigned int*)&flt;
h = [NSString stringWithFormat:@"0x%08X", *fp];
This may or may not be in IEEE-754 notation, etc etc. It also assumes sizeof(float) == sizeof(int) == 4
|
6,756,155 | 6,756,210 | Creating a decorateable effective event handling type in c++ | This has been really killing me for the last couple of days now.
I effectively have something like what Szymon Gatner explained in his fantastic article, found here. (Check out the EventHandler class in the demo code there)
This is one of the few articles I've found on the web that do a good job explaining
how to crea... | Perhaps one option would be to create a templated public function that preserves type information, plus a virtual protected function for actually registering the handler. That is:
class event_source {
protected:
struct EventAdapter {
virtual void invoke(EventBase *) = 0;
virtual ~EventAdapter() { }
... |
6,756,476 | 6,756,604 | How do I manage directories' paths with std::map or set? | I'd like to use stl::set to put some directory paths.
The set has some special directory paths which I put.
And I should find the special parent of some input paths.
There is the code. And I commented some points.
set<wstring> special_directories;
void WhoIsMySpecialParent(const wstring& f)
{
set<wstring>::const_i... | Using std::set<T>::upper_bound() simply finds the lexicographical sorted sorted index that is the mathematical upper bound in the tree data-structure that std::set uses. In this case "/etc" was the upper bound to "home/benjamin" since if you count through the alphabet, "home/benjamin" will come before "home/benjamin/d... |
6,756,532 | 6,756,674 | How do C++ functor constructors get called when used with for_each or std::transform | I've never used c++ functors before and so I'm just trying to understand how they work.
e.g. suppose we have this functor class
class MultiplyBy {
private:
int factor;
public:
MultiplyBy(int x) : factor(x) { }
int operator () (int other) const {
return factor * other;
}
};
Using it like this ... | You can think of transform being structured like this:
void transform(Iterator b, Iterator e, Functor f)
{
for(;b != e; ++b)
{
*b = f(*b);
}
}
The functor is passed by value into the function.
So when you call like this:
std::transform(array, array + 5, array, MultiplyBy(3));
Here you have created... |
6,756,931 | 6,756,957 | Difference between try-catch syntax for function | I came across this syntax recently for try-catch for function.
struct A
{
int a;
A (int i) : a(i) // normal syntax
{
try {}
catch(...) {}
}
A () // something different
try : a(0) {}
catch(...) {}
void foo () // normal function
try {}
catch(...) {}
};
Both syntax are valid. Is there a... | The First Syntax:
The scope of the try block starts after the Member Initialization list has been completed, So any exception thrown during Member Initialization will not be caught by this try-catch block.
The second syntax:
It ensures that if an exception gets thrown during Member Initialization list then you are able... |
6,757,536 | 6,757,562 | Structure member alignment in GCC | I'm porting an msvc project, which has several libraries and each library has specific structures member alignment. Using default alignment caused lots of fatal misalign problems and googling told me that I can solve this issue by setting alignment for each struct / class / union manually with the __attribute__ ((align... | I don't think there should be an issue with that. Just remeber that unaligned access (4 byte minimum I think on most systems) will cost you (although you save space albeit not much in some situations). The structures themselves have the attribute and the compiler will do all the pointer arithmetic so as long as the hea... |
6,757,691 | 6,757,830 | Partial Specialization of tuple contents with variadic arguments | Currently, I'm trying to get some code to react differently to different types. This isn't the exact code, but it gets the message across.
template<class A, class B>
struct alpha {
enum { value = 0 };
};
template<class T, class... Args>
struct alpha<std::tuple<Args...>, T> {
enum { value = 1 };
};
// This gets ig... | If you compile using clang, it helpfully reports that (2) and (3) are unusable. The warning for (3), which you expect to be selected, is as follows:
warning: class template partial specialization contains a template parameter that can not be deduced; this partial specialization will never be used
struct alpha<std::tu... |
6,758,266 | 6,761,162 | How to synchronize QWidgets with menu bar? | I am new to Qt creator. I have a stacked widget with 3 pages. I also have a menu bar that contains : open \\ create. The QWidget contains 2 pages. I would like to ask how can I synchronize Open with first page and create from menu bar with second page from stacked widget?
I did write: ui->stackedWidget->show(); but it'... | You have to declare two slots in your MainWindow class. For instance:
class MainWindow : public QMainWindow
{
...
public slots:
void slotOpen() ;
void slotCreate() ;
...
} ;
Then, in your MainWindow constructor (assuming your menu actions are actionOpen and actionCreate):
connect (ui -> actionOpen, SIGNAL(... |
6,758,402 | 6,758,640 | Will a long filter string affect the search perfomance in ldap? | Will a long filter string affect the search perfomance in ldap?
Will it affect the search time?
Thanks.
| Off course it will, simply because its large :)
I would suggest 2 things:
1) Post a example search of what your trying to do in the post, perhaps you definition of large is different from other ppl.
2) Benchmark yourself to see, if the search takes 1 second and thats ok then you have solved your problem.
On a side note... |
6,758,717 | 6,759,059 | Explicit move constructor? | The explicit keyword is recommended for all most constructors which can be called with one argument, except for copy constructors.
For copy constructors, it has an use (to forbid implicit copying via function call, return, etc), but it's not what's usually wanted.
What about move constructors? Is there any reasonable u... | An explicit move constructors can affect compatibility with e.g. Standard algorithms. For instance, std::swap<T> requires that T be MoveConstructible. In turn, MoveConstructible is specified in terms of an expression, namely T u = rv; (where rv is an rvalue of type T).
If there is neither a non-explicit copy constructo... |
6,758,981 | 6,759,038 | Why does boost::scoped_ptr not work in inheritance scenario? | When using boost::scoped_ptr to hold a reference, the destructor of the derived object is not called. It does when using boost::shared_ptr.
#include "stdafx.h"
#include <iostream>
#include "boost/scoped_ptr.hpp"
#include "boost/shared_ptr.hpp"
using namespace std;
class Base
{
public:
Base() { cout << "Base const... | The reason why it works for shared_ptr is because it implements a special constructor and a reset() method that look like this:
template<class T>
class shared_ptr
{
public:
// ...
// Note use of template
template<class Y> explicit shared_ptr(Y * p);
// ....
// Note use of template
template<class... |
6,759,560 | 6,759,763 | Boost::test and mocking framework | I am using boost::test and need to use a mocking framework with it. Does anyone have any recommendations?
| I recently did a search for unit testing and mocking frameworks for my latest project and went with Google Mock. It had the best documentation and seems fairly well featured (although I haven't created very complex mock objects yet). I initially was thinking of using boost::test but ended up using Google Test instead (... |
6,759,592 | 6,761,962 | How to enable __int128 on Visual Studio? | When I type __int128 in a C++ project in Visual Studio, the editor changes color of __int128 to blue (like keyword).
But when I compile the source, the folowing error appears:
error C4235:
nonstandard extension used : '__int128' keyword not supported on this architecture
How can I enable __int128 on Visual Studio?
| MSDN doesn't list it as being available, and this recent response agrees, so officially, no, there is no type called __int128 and it can't be enabled.
Additionally, never trust the syntax hilighter; it is user editable, and thus likely to either have bogus or 'future' types in it. (it is probably a reserved word howeve... |
6,759,902 | 6,760,227 | C++ queue doesn’t like less than 8 char*s | A program written in C++ reads from a network socket and then writes to local socket. It uses a separate thread for the “read”.
When a message is read, it is put into a char * queue (using mutex from the boost libraries to make it thread-safe).
Meanwhile the queue is checked to see if it is empty, if it isn’t, then the... | std::queue has no such limitation. What you are seeing must be the result of problems in your code. (You say yourself, that you never take in less than 8 bytes?!)
Edit: What seems odd in the code samples is memory management (explicit calls to destructors, instead of delete; the memory of the char* -s doesn't seem to b... |
6,759,903 | 6,759,952 | An issue about c/c++ Segmentation fault | I wrote a simple program to test array pointer:
#include <iostream>
using namespace std;
int main(){
int (*array)[10];
int i, j;
for (i = 0; i < 10; i++){
for (j = 0; j < 10; j++)
array[i][j] = 1;
}
for (i = 0; i < 10; i++){
f... | array is a pointer to an array, which you apparently already know. However, you never allocated memory for the actual array, i.e. your pointer is pointing "nowhere". You are trying to access something that does not exist, which often leads to segmentation fault.
For example, you can declare an actual array
int array10x... |
6,759,910 | 6,760,065 | Preventing Rounding Errors | I was just reading about rounding errors in C++. So, if I'm making a math intense program (or any important calculations) should I just drop floats all together and use only doubles or is there an easier way to prevent rounding errors?
| Obligatory lecture: What Every Programmer Should Know About Floating-Point Arithmetic.
Also, try reading IEEE Floating Point standard.
You'll always get rounding errors. Unless you use an infinite arbitrary precision library, like gmplib. You have to decide if your application really needs this kind of effort.
Or, you ... |
6,760,016 | 6,760,067 | Deleting an uninitialised object in C++ | In my header file I declare a variable within the scope of a class:
FaultModel<double> *fm_req_set_odom_px;
...which is conditionally initialised in the class constructor, depending on the value of a configuration file:
const char *configModel = ConfigReader->ReadString("FaultModel");
if (strcmp(configMo... | delete NULL; is guaranteed to be a no-op, so a manual check is not necessary. However, an unitialized pointer variable is not NULL, so you must explicitly set it to NULL if the condition fails:
if (strcmp(configModel, "cyclic") == 0)
fm_req_set_odom_px = new CyclicFaultModel<double>();
else
fm_req_set_odom_px =... |
6,760,133 | 6,760,667 | How to make linker prefer implementation from a given location | I need a way to make linker prefer one implementation instead of another. My use case is the following: I'm writing unit tests, and I need to mock some objects. The problem is those objects are in 'main' library, which I cannot throw away even in debug, because many of SDK things live there.
So I've implemented those ... | Usually mocking isn't done on linking stage but is solved in your code. Dependency Injection is one of the preferred techniques. That is, you are supposed to model your code so you can choose between a real and mock implementation.
For example you want to create an object A in your code. One way is to have two differen... |
6,760,668 | 6,760,990 | Why std::pair calls explicit constructors in assignment | Consider the following code:
#include<iostream>
#include<utility>
struct Base
{
int baseint;
};
struct Der1 : Base
{
int der1int;
Der1() : der1int(1) {}
explicit Der1(const Base& a) : Base(a), der1int(1)
{
std::cerr << "cc1" << std::endl;
}
};
struct Der2 : Base
{
int der2int;
... | I am not sure that I understand the question, but basically you are asking why two unrelated std::pair can be implicitly convertible even if the instantiating types are not implicitly convertible. That is, why the implicitly convertible property of the instantiating types does not propagate to the pair.
The standard do... |
6,760,745 | 7,122,673 | How to implement painting (with layer support) in OpenGL? | situation
I'm implementing a height field editor, with two views. The main view displays the height field in 3D enabling trackball navigation. The edit view shows the height field as a 2D image.
On top of this height field, new images can be applyed, that alter its appearence (cut holes, lower, rise secific areas). Th... | Here is what I ende up:
I use the PickIntersector of the Visualisation Library to pick agains the Height Field Image in the edit view.
This yealds local coords of the image.
There are transformed to uv coords, wich in turn get transformed into pixel coords.
This is done when the user presses a mouse button and continue... |
6,760,773 | 6,760,837 | Project Euler:#14 Integer overflow and Stack overflow | unsigned long long terms;
unsigned long long test;
unsigned long long digit = 1;
unsigned long long max = 0;
//cout<<sizeof(long)<<" "<<sizeof(int)<<endl;
//cout<<digit<<endl;
for(;digit<1000000;++digit)
{
terms = 1;
test = digit;
while(test>1)
{
if(0==(test%2))
{
test /=2;
... | This is the Collatz Conjecture. Consider using memoization to solve the problem by storing the lengths of the chains you've seen for (e.g. if 6 gives a chain length of 7 and you encounter 6 when processing change N, then you can just add 7 to the chain length so far and immediately return).
|
6,760,968 | 6,777,199 | How to capture a frame in MFC | I have a video file in my Project.
When I am playing it in my application, I want to capture it frame by frame using Animation Control in MFC.
Regards
| I see no reason to do this in 2011, but since you asked: you use Animate_Seek() for each frame, and use GetDC() / BitBlt() to capture an image ('screenshot') of the control for each frame.
|
6,760,971 | 6,761,024 | Why this code doesn't compile? | Is there any difference in these codes:
std::string dirName = argv[1];
MyRecordDatabaseType myDB(Selector<std::string>((std::string)dirName));
and
std::string dirName = argv[1];
MyRecordDatabaseType myDB(Selector<std::string>(dirName));
I have no idea why the second version doesn't compile.
The compiler tells me:
er... | Yes, the difference is that this line
MyRecordDatabaseType myDB(Selector<std::string>(dirName));
can also be written like
MyRecordDatabaseType myDB(Selector<std::string> dirName);
and is a declaration of a function myDB that returns MyRecordDatabaseType.
See C++ most vexing parse
|
6,761,122 | 6,761,172 | restriction on friend function | According to the text I am referring to (The Complete Reference by Herbert Schildt) a derived class doesn't inherit friend functions and friend functions may not have a
storage-class specifier. That is, they may not be declared as static or extern. Why?
|
a derived class doesn't inherit friend functions? […] why?
Because that would break encapsulation: the derived class couldn’t control its friends any longer so it effectively cannot control who has access to its internals.
they may not be declared as static or extern, why?
Because static would make no sense (it onl... |
6,761,259 | 6,761,431 | To polymorph or to incapsulate, this is the question! (C++) | I need to store a polymorphic object (let's say Polygon) inside another object (let's say Simulation). At the same time I want to keep encapsulation of Simulation.
class Polygon {
public:
virtual double area() { return 0; }
};
class Square : public Polygon {
public:
Square(double edge) : edge_(edge) {}
virtual ... | Add a clone function to Polygon (and a virtual destructor!). It is a good idea to ensure that Polygon is abstract so make sure at least one function is pure virtual.
Your Simulation class will require a copy constructor, destructor and assignment operator.
Note that the Square clone function can return a Square* even ... |
6,761,313 | 6,762,500 | QtConcurrent::blockingMapped() and std::vector<> bug | It seems that QtConcurrent works fine with QT containers (QList and QVector), but fails with the STL containers, as opposed to what is claimed in the documentation
Here are the dummy functions I want to use on my containers :
void addOne(int & i)
{
++i;
}
int addOneC(const int & i)
{
return i+1;
}
Examples o... | I think you should explicitly give the type of the container to the blockingMapped.
int main( int argc, char** argv )
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(4);
v.push_back(3);
std::vector<int> v1 = QtConcurrent::blockingMapped<std::vector<int> >(v, addOneC);
}
Compi... |
6,761,453 | 6,761,628 | How to load a serialized boost::variant? | I'm not able to use boost::serialization because it has library dependencies so I'm trying to figure out a way to do it myself. It doesn't matter if that means copying from boost::serialization.
After reading this answer to a similar question, I had a look at boost/serialization/variant.hpp and found save() function wh... | If you were to remove the serialization stuff from a copy of boost/serialization/variant.hpp (apart from the Archive template parameter) - i.e. get throw your own exception types and change e.g.
ar >> BOOST_SERIALIZATION_NVP(which);
// to:
ar >> which;
Then it looks like you should be able to replace Archive with std... |
6,761,774 | 6,761,867 | Which kind of (auto) pointer to use? | I came accross several questions where answers state that using T* is never the best idea.
While I already make much use of RIIC, there is one particular point in my code, where I use T*. Reading about several auto-pointers, I couldn't find one where I'd say that I have a clear advantage from using it.
My scenario:
cla... | Personally I think a raw pointer (or reference) is okay here. Smart pointers are concerned with managing the lifetime of the object pointed to, and in this case MyMapper isn't managing the lifetime of that object, MyClass is. You also shouldn't have a smart pointer pointing to an object that was not dynamically allocat... |
6,761,870 | 6,762,333 | Organizing a task-based scientific computation | I have a computational algebra task I need to code up. The problem is broken into well-defined individuals tasks that naturally form a tree - the task is combinatorial in nature, so there's a main task which requires a small number of sub-calculations to get its results. Those sub-calculations have sub-sub-calculations... |
there's a main task which requires a small number of sub-calculations to get its results. Those sub-calculations have sub-sub-calculations and so on. Each calculation only depends on the calculations below it in the tree (assuming the root node is the top). No data sharing needs to happen between branches. At lower le... |
6,762,610 | 6,763,315 | Fast memory access in C++? | What should I take in consideration when developing a game in terms of fast memory access in C++?
The memory I load is static so I should put in in a continuous block of memory right?
Also, how should I organize the variables inside structs to improve performance?
| Memory Performance is extremely vague.
I think that what you are looking for is about handling the CPU Cache as there is a factor of about 10 between an access in the cache and an access in the main memory.
For a complete reference on the mechanisms behind the cache, you might wish to read this excellent serie of artic... |
6,762,655 | 6,762,702 | Array declaration in the .h file, is it a good idea? | I am working in C++ and want to declare an array in the private section of the header file. Now that I am thinking about it, I thought doing so was bad practice? I would think doing this would cause multiple declarations everywhere the header is included? Almost like a mem leak?
Is this correct? I'm not sure what the s... | (Assuming non-member, since you didn't say anything about an encapsulating type. If your use of the term "private" was to be taken literally, then please clarify your question.)
You won't get a memory leak; you'll get multiple definition errors.
Put all array definitions in a source file, yes, but you can "forward dec... |
6,762,718 | 6,762,772 | What is the rule for declaration before use in C++? | My course notes say "C++ requires declaration before use in a block and among types but not within a type."
Is this what it means?
int f() {
if (i)
return i;
int i = 1; //allowed?
return 0;
}
//not allowed?
int g() {
if (i)
return i;
return 0;
}
int i = 1;
| No. Both your examples are "in a block" and neither of those is allowed. If you try compiling your example code you'll get an error immediately.
However, this would be allowed:
class Foo {
int f() {
return i;
}
private:
int i;
};
This is within a type and that's the important distinction.
|
6,762,926 | 6,762,994 | Deleting an object which was created in a DLL | I need some clarification regarding runtime/heap issues when deleting an object which was created in a DLL. It needs some introduction before I come to my questions...
In my project a DLL (which is specified by its name) returns a new Grabber object. In an earlier version of my code, the DLL exported a function like th... | The DLL is reference counted, not loaded twice, and when you use LoadLibrary then it's only loaded once anyway and they will use the same heap. The static function is the normal solution to this problem.
|
6,762,996 | 6,763,218 | Const-correctness for C++ classes | class SomeClass {
public:
void Render() const;
private:
mutable Cache m_some_cache;
};
Is the class above const-correct? When can I safely say "This operation doesn't change the internal state of an instance"?
In the above example SomeClass is something that renders stuff on the screen. It uses a cache (... | Think of it this way. This is perfectly valid:
void Type::print_self () const {
std::cout << *this << std::endl;
}
You aren't modifying the object itself, so the use of the const qualifier is perfectly valid. This method is modifying std::cout, but that doesn't count as far as the constness of Type::print_self() g... |
6,763,260 | 6,763,293 | cv-qualifiers and implicit type conversion | In the code,
const int x = 3;
int y = 0;
y += x;
Is there any need to remove the const from x before doing the addition or is this maybe done implicitly in the addition operator definition?
| Firstly, the += operator is an assignment operator (compound assignment). Its behavior though is equivalent to y = y + x combination (except y is evaluated only once).
Secondly, when used as an operand of addition operator (including the RHS of += as in your example) x participates in the expression as an rvalue, i.e. ... |
6,763,262 | 6,763,443 | c++ get version from .rc into code |
Possible Duplicate:
How do I read from a version resource in Visual C++
in my c++ project i've added a .rc file where I can store the file version, the executable description, copyright, etc..
and is ok, I compile, i go to the explorer -> file property and I see all the fields in the form.
My question is: if I need ... | Windows provides a set of API calls for retrieving the version information from executable files. The following snippet of code should help you get started.
bool GetVersionInfo(
LPCTSTR filename,
int &major,
int &minor,
int &build,
int &revision)
{
DWORD verBufferSize;
char verBuffer[20... |
6,763,316 | 6,763,327 | Segmentation Fault with delete even using virtual destructor | I am getting segmentation fault while deleting an objected, being referenced by the pointer of the base class, even when I have declared the destructor virtual!
here is my Code
class Shape
{
public:
virtual ~Shape()
{
cout<<"Shape destructor is called!"<<endl;
}
};
cl... | You can only delete an object allocated with new.
myShapePtr does not point to an object allocated with new, it points to myLine, which is a local variable.
As a local variable, myLine has automatic storage duration. It will be destroyed automatically when the } that ends the block in which it is declared is reached.
|
6,763,386 | 6,792,288 | Unable to change round robin time quantum in real time linux | I'm writing a C++ program on SUSE Linux Real Time and is trying to gather timing statistics on its round robin(RR) scheduling policy. I am able to set the policy to RR via
#include <sched.h>
...
struct sched_param sparms;
sparms.sched_priority = 99;
if (sched_setscheduler(0, SCHED_RR, &sparms) < 0){
perror("sched_se... | It seems that the ability to control the round-robin time quantum has been removed from the Linux real-time scheduler.
Looking at the source (kernel/sched_rt.c), the timeslice counter is restored to a constant value (DEF_TIMESLICE, defined as 0.1s) when it expires in task_tick_rt(), so there is no way to change it dyn... |
6,763,583 | 6,763,629 | How do I check/change my sound card's sample rate? | I'm playing around with XAudio2 to send PCM format waves to my soundcard, and I encountered a problem which made me think about this question. I created a .csv file with MATLAB of a sine wave at 440 Hz, and at first I had sampled it at 1 KHz (for 1 second).
My C++ program would then load that file and send the buffer t... | The nyquist frequency at 1kHz sample rate is only 500Hz. I'm not surprised at all it sounded terrible. Suppose you had a sample rate of 1kHz and you played a 500Hz sound. Your output would be a square wave. - + - + - + with nothing in between, as you don't have enough samples. As you approach the nyquist frequency... |
6,763,627 | 6,763,859 | What is the relation between double pointer and 2d array? | void displayMatrix(int **ptr)
{
printf("%d %d \n",**ptr,*(*ptr+1));
*ptr++;
printf("%d %d \n",**ptr,*(*ptr+1));
}
Is it a correct way to pass 2x2 array to function ?
displayMAtrix(array);
| If you have a 2D array with automatic storage duration (e.g. int matrix[2][2];), then no, this is not the correct way to pass a 2D array.
int f ( int, char ** )
{
int matrix[2][2];
displayMatrix(matrix);
}
To be standard compliant (there are other ways to make it work, but this is the standard, recommended way), y... |
6,763,646 | 6,763,895 | istream::tellg() returns -1 when used with my custom streambuf class? | I'm trying to create an istream that reads directly from a raw memory buffer.
I found a nice way to do this in another post on here:
class membuf : public basic_streambuf<char>
{
public:
membuf(char* p, size_t n) {
setg(p, p, p + n);
}
};
Then I create my istream using this membuf:
me... | The functions tellg and seekg depends on protected virtual functions seekoff and seekpos, that you would have to implement in your membuf class.
The defaults in basic_streambuf just returns pos_type(off_type(-1)) for all calls (which might be equal to -1 for many implementaions).
|
6,763,731 | 6,763,952 | Handles to objects in central registry with automated cleanup | I have a central repository of objects Base which can produce various things. Base must keep a pointer to all objects, as a central update method has to iterate through all objects created by the Base instance. However, if the last handle to an object is destroyed, there is no need to keep it around any more so Base sh... | How about this: Your class Base outputs shared_ptrs through the Make* functions, but only stores weak_ptrs internally. The update loop can check whether the weak pointer is still valid and remove it if not.
Your final requirement that deleting the base will also kill existing objects is a bit trickier. You could go thr... |
6,763,754 | 6,765,520 | GLSL rendering in 2D | (OpenGL 2.0)
I managed to do some nice text-rendering in opengl, and decided to make it shader-designed.
However, rendered font texture that looked nice in fixed pipeline mode looked unpleasant in GLSL mode.
In fixed pipeline mode, I don't see any difference between GL_LINEAR and GL_NEAREST filtering, it's because the... |
though for performance reasons, as you can see, I'm writing constant values into the shader code
That's not going to help your performance. Uploading a single matrix uniform is pretty standard for most OpenGL shaders, and will cost you nothing of significance in terms of performance.
Seems like matrix/vertex multipl... |
6,763,891 | 6,764,127 | Using mutex locks incorrectly in C++ somehow | I have the following code to try (and fail) to protect a critical region in my code. Basically I want a print statement to be fully executed by any thread before some other thread prints another statement.
In main.h:
pthread_mutex_t printer_mutex;
In main.c - the first thing the program does:
pthread_mutex_init(&prin... | I believe the problem is in defining the mutex variable in the header file. That way every compilation unit gets its own version of such variable, and you just lock different mutexes. Simply do this:
// .h header file: declare
extern pthread_mutex_t printer_mutex;
// one of the .c/.cpp files: define
pthread_mutex_t pr... |
6,763,934 | 6,764,232 | Creating some sort of list of C++ objects in C++/CLI | I am trying to create a list/collection of C++ objects in C++/CLI and I have tried various ways but nothing seems to work (errors at compile time).
I have tried:
List<MyCppObject*> ^myList; //Does not allow non-.NET objects
ArrayList ^myList;
...
myList->Remove(myCppObject); //cannot convert parameter 1 from 'MyCppObj... | To store native objects/pointers you must use native collection classes. If you want the collection class to maintain allocation/deallocation use <MyCppObject>, or use <MyCppObject*> if you would maintain the memory allocation (i.e. collection class would hold the pointers only).
STL/CLR classes would do something oppo... |
6,764,168 | 6,764,207 | What does double not (!!) used on a non-boolean variable do? |
Possible Duplicate:
Double Negation in C++ code.
I am working with production code where I have run across statements like this a few times:
Class.func(!!notABool);
The first couple of times I dismissed it as a programmer quirk (maybe to emphasize that it is a conditional statement rather than a number being passed... | For primitive types, yes, it's essentially equivalent to:
!(notABool != 0)
which in turn is equivalent to:
(bool)notABool
For non-primitive types, it will be a compiler error, unless you've overloaded operator!, in which case, it might do anything.
|
6,764,195 | 6,764,332 | Is this code legal? (C++0x move semantics) | I'm curious as to whether this code is legal in C++0x. Specifically, will the object declared in the function move_it() be properly moved to the object declared in main()?
#include <iostream>
#include <string>
#include <tr1/memory>
using namespace std;
class x
{
public:
x() { cout << "create " << this << endl; }
... | No, it is returning a reference to a local object, just like with an lvalue reference.
Just return it by value and let x's assumed move constructor pick up the rvalue. When you return by value, the returned object is an rvalue.
If you are lucky, the NRVO optimization will kick in (just like before) and elide the copyi... |
6,764,776 | 6,764,952 | How to save a session in a Qt application? | I made this tool in Qt Creator where i have to enter some data in spin boxes and combo boxes. Each of these boxes have a default value when I open my tool. But I would like to implement a function to save the session of the application, i.e. if i modify some values in the boxes i can save them and when I open my applic... | Use QSettings , it's usage is explained in the page
|
6,764,790 | 6,769,603 | Which model to subclass / view to use for a list of custom objects | I don't have enough experience with Qt yet to make a good design choice. Any help by experienced Qt programmers would be very appreciated.
I'm trying to find out which model to subclass, which view to use, what delegate subclassing / extending I should do...
My problem is similar to: I have these zones I would like t... | QDataWidgetMapper is a slightly different thing. It is a way to display one item from a Model (ex. QStandardItemModel), using custom controls. You can read more about it here, with accompanying snapshots and an example of how to implement one.
While it is certainly cool, I don't think it is what you want here. Mostl... |
6,764,991 | 6,765,080 | Performance impact of QueryPerformanceCounter | Is there a performance impact from calling QueryPerformanceCounter over a less high-resolution timing method in Windows?
| Although old, this Dr Dobb's article gives a nice summary of your options and their costs, pros and cons (see the tables right at the end), including QPC.
TBH, to get real timings for your situation, use a profiler (like AMD's CodeAnalyst) or something like Dr Fog's performance monitor(site, which also has some other t... |
6,765,057 | 6,765,091 | Using modulus operator to keep within indices of container | Assume I have a vector v with m elements in it, and a random access index to the vector called i.
When I increment the index, if it goes out of bounds, I want to index the first (zeroth) element. Similarly, when I decrement the index, if the index is < 0, I want to index to last element. At the moment I'm only moving t... | The trick for handling MOD is this, which works with positive as well as negative numbers:
val = ((val % mod_val) + mod_val) % mod_val;
For example, assume we want to keep value between 0 and 359 inclusive. We could use this:
val = ((val % 360) + 360) % 360;
Here's a simple example in C++.
int getmod(int val, i... |
6,765,092 | 6,765,333 | Convert hex stream to GIF | How do I create a .gif file from the following HEX stream:
0d 0a 0d 0a 47 49 46 38 39 61 01 00 01 00 80 ff 00 ff ff ff 00 00 00 2c 00 00 00 00 01 00 01 00 00 02 02 44 01 00 3b
3b is the GIF file terminator
I'm trying to do it following the guide at http://en.wikipedia.org/wiki/Graphics_Interchange_Format#Example_GIF_fi... | You can do it in the shell, using GNU echo:
$ /bin/echo -n -e "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\xff\x00\xff\xff\xff\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b" > foo.gif
$ identify foo.gif
foo.gif GIF 1x1 1x1+0+0 8-bit PseudoClass 2c 36B 0.000u 0:00.000
You can also use th... |
6,765,145 | 6,765,239 | Multiple Inheritance, C++ and Same Method Signature in Multiple Super Classes | I have no experience in C++, and I come from a Java background. Lately, I was asked in an interview on why Java would not allow multiple inheritence and the answer was pretty easy. However, I am still curious on how C++ deals with that since it allows you to inherit from more than one class.
Specifically, say there is ... | The compiler will flag this kind of situation (i.e., attempting to call (some instance of RoboticsEngineer).buildRobot()) as an error.
This happens because the derived object has got a copy of both base objects (a MechanicalEngineer instance and an ElectricalEngineer instance) inside of itself and the method signature... |
6,765,201 | 6,765,354 | engOpen returns Null | I'm having a problem when I try to call a Matlab funcion from my C++ code.
When I call engOpen, it always returns NULL.
Here is the code:
Engine *m_pEngine;
m_pEngine = engOpen(NULL);
if(m_pEngine == NULL)
{
cout << "Error" << endl;
exit(1);
}
Does somebody know how to solve this?
Thanks !!!
| If you look at the engOpen documentation it says:
On Windows systems, engOpen opens a COM channel to MATLAB. The MATLAB software you registered during installation starts. If you did not register during installation, on the command line you can enter the command:
matlab /regserver
I'm not sure that is your problem, bu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.