question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,778,278 | 1,778,287 | If you had the time and inclination to create a programming language, what characteristics would it have? | Just curious. If you had the time and inclination to create a programming language, what characteristics would it have?
One language I would like to see would borrow as much from the syntax of Python as possible but compile to machine code that runs as fast as C or C++.
| A mix of COBOL and XML, for the lulz
<program>
<data>
<const>
<name>myStr</name>
<value><[CDATA[Hello, World!]]></value>
</const>
</data>
<sub>
<name>main</name>
<params />
<return />
<code>
<call>
<name>writ... |
1,778,279 | 1,778,310 | Q_Object with no type | The error I am receiving:
g++ -c -g -I/usr/lib/qt-3.3/include TCPEchoServer.cpp
Product.h:22: error: ISO C++ forbids declaration of âQ_Objectâ with no type
Product.h:24: error: expected â;â before âvoidâ
make: *** [TCPEchoServer.o] Error 1
I'm using QT 3.3.
What am I missing...? T___T
#include <string>
#include... | You are missing the correct case for the macro, it should be Q_OBJECT.
|
1,778,487 | 1,779,076 | Python subclass with C++ baseclass | I have some C++ I have exposed to Python through SWIG. In there is a base class with a single pure virtual function.
In Python, I import my module and define a class that uses the abstract class as base.
import mymodule
class Foo(mymodule.mybase):
...
In that module is also a manager class, I want to add my new de... | My guess is that Foo is not derived from mybase in the eyes of the C++ environment. I'm not sure if SWIG can pull this off since it requires a bidirectional understanding of inheritance - Python class uses C++ class as base and C++ code recognizes the inheritance relationship. I would take a serious look into Boost.p... |
1,778,491 | 1,778,558 | How does one return a local CComSafeArray to a LPSAFEARRAY output parameter? | I have a COM function that should return a SafeArray via a LPSAFEARRAY* out parameter.
The function creates the SafeArray using ATL's CComSafeArray template class.
My naive implementation uses CComSafeArray<T>::Detach() in order to move ownership from the local variable to the output parameter:
void foo(LPSAFEARRAY* ps... | The problem is that you set the receiving CComSafeArray's internal pointer directly.
Use the Attach() method to attach an existing SAFEARRAY to a CComSafeArray:
LPSAFEARRAY ar;
foo(&ar);
CComSafeArray<VARIANT> sa;
sa.Attach(ar);
|
1,778,503 | 1,779,361 | VC++ 'Generating Code', what does it mean? | WHen compiling in visual studio the compiler outputs this at what seems to be its own discretion:
1>Generating Code...
what is it doing here exactly?
| It is doing what it says: it is generating the machine code. Many compilers translate C/C++ sources into some intermediate internal representation that is later used as the source to generate the actual machine code. Visual C++ compiler (as many other compilers) does this in batches: first it translates a bunch of sour... |
1,778,619 | 1,778,624 | encoding conversion from JIS X 208 to UNICODE | How can I convert a JIS X 208 encoded string into UNICODE in C++? A VC++ specific answer would be helpful.
The bigger problem that I am finding difficulty in understanding is that there are too many encodings for Japanese characters. JIS itself has many versions, then there is Shift-JIS. It would be great if some one ... | The ICU project contains many functions for converting from and to Unicode. It'll work on most OS's, including Windows. It'll handle conversions to/from pretty much all the codepages out there.
From what I can see, JIS X 0208 and JIS 0208 appear to be 2 variations in the name for the same thing, i.e. the actual codep... |
1,779,149 | 1,779,188 | Will there be any performance issue using C++ inside C#? | I have a C++ program which does text processing on 40k records. We developed this program in C++ because we thought it would be faster. Then I used/executed this C++ part inside my C# program using the process-execute but the problem is we feel like we lost control of the execution flow: not able to debug the C++ part.... | You have a few options here:
Write the processing in .NET and measure the performance. If it is unacceptable try to optimize it. If it is still too slow you revert to unmanaged code. But thinking that unmanaged code will be faster and for this reason writing unmanaged code without measuring IMHO is wrong approach.
As ... |
1,779,313 | 1,779,320 | Returning a pointer vs. passing a reference to an object to store the answer in C++ | I have general question regarding the use of pointers vs. references in this particular scenario.
Let's say that I have a function that is going to do some computation and store the value inside an object for later use by the caller. I can implement this by using either pointers or references.
Although, I would prefer ... | The second approach is probably preferable because there is no possibility of a memory leak, in the event you forget to delete the returned pointer.
It's usually good practice to code in such a way that each function or object which allocates heap memory also deallocates that memory. Your first example violates that p... |
1,779,362 | 1,779,411 | How could I apply a genetic algorithm to a simple game that follows rollercoaster tracks? | I have free-rein over what I do on a final assignment for school, with respect to modifying a simple direct-x game that currently just has the camera follow some rollercoaster rails. I've developed an interest in genetic algorithms and would like to take this opportunity to apply one and learn something about them. H... | From your query, it seems like that you want to use Genetic Algorithms to get optimized roller coaster rail tracks. For any optimization problem:
you will first need to break down your desired solution into its components or design variables.
Once you have the "variables" you need to look at formulating a objective f... |
1,779,438 | 1,779,472 | Error with `QObject` subclass and copy constructor: `QObject::QObject(const QObject&) is private` | The following compile errors is what I have:
/usr/lib/qt-3.3/include/qobject.h: In copy constructor Product::Product(const Product&):
/usr/lib/qt-3.3/include/qobject.h:211: error: QObject::QObject(const QObject&) is private
Product.h:20: error: within this context
HandleTCPClient.cpp: In member function int Handler::Ha... | Product is a subclass of QObject, which cannot be copied. Your code is attempting to copy it somewhere (perhaps in productDetails(tempProduct)) and this causes the error. Perhaps you could pass it to your function by const reference instead; or perhaps some redesign of your program is needed.
Your compiler is telling y... |
1,779,494 | 1,779,558 | Dynamic Allocation of an Array of Pointers to Objects | This question is in C++.
I am trying to dynamically allocate an array of pointers to objects.
I know I can use a vector container but the point of the exercise is not to...
Here is the code:
void HealthClub::AddHealthClubDevice ( char* HealthClubDeviceName )
{ //We added NumberOfDe... | Can't reproduce your problem. Specifically, here's all of the skeleton code I compiled and ran successfully -- your method plus the minimal scaffolding to make it into a complete program:
#include <iostream>
struct Device {
char* name;
Device(char* n) {name = n;}
};
struct HealthClub {
int NumberOfDevices;
D... |
1,779,522 | 1,779,582 | Unable to correct error in C++ code | I am unable to detect the error in the following C++ program.
The code defines a Graph class.
#include <vector>
#include <list>
using namespace std;
class Neighbor {
public:
int node_id;
float edge_cost;
float price;
Neighbor(int&,float&,float&);
};
Neighbor::Neighbor(int& node_id, float& edge_co... | Try to replace the line of code from
vector<list<NS> >::iterator node_iterator;
to
typename vector<list<NS> >::iterator node_iterator;
You also need to implement copy-constructor for Neighbor class if you are going to use it as template argument for Graph. This is because you define Neighbor constructor manually and... |
1,779,545 | 1,779,586 | Stack allocation limit for programs on a Linux 32 bit machine | In C++ how much can the stack segment grow before the compiler gives up and says that it cannot allocate more memory for stack.
Using gcc on a linux (fedora) 32 bit machine.
| Under UNIX, if you are running bash run
$ ulimit -a
it will list various limits including stack size. Mine is 8192kb. You can use ulimit to change the limits.
Also, you can use ulimit() function to set various limits from within your program.
$ man 3 ulimit
Under Windows see StackReserveSize and StackCommitSize
In pr... |
1,779,608 | 1,779,626 | integer automatically converting to double but not float | I have a function like below:
void add(int&,float&,float&);
and when I call:
add(1,30,30)
it does not compile.
add(1,30.0,30.0) also does not compile.
It seems that in both cases, it gets implicitly converted to double instead of float.
So, do you suggest that it is better to re-define add as add(int&,double&,double&)?... | Your function takes its parameters by reference, not by value, and you can't pass constant integer/floating-point values by non-const reference. You should either change your function to take its parameters by value, or pass actual variables instead of constants, e.g.:
int x = 1;
float y = 30, z = 30;
add(x, y, z);
Y... |
1,779,670 | 1,779,717 | Show colored compilation errors in C++ on Terminal | Is there any way to show compilation errors in colors on the terminal?
I mean when we do "g++ filename.cpp", is there a way to show the compiler messages in colors? By default it is always in Black color. But if we have a lot of error messages, then it helps to have them in different colors (just like the code is highl... | http://schlueters.de/colorgcc.html
http://colorifer.sourceforge.net/
|
1,779,685 | 1,779,788 | What is ->* operator in C++? | C++ continues to surprise me.
Today i found out about the ->* operator. It is overloadable but i have no idea how to invoke it. I manage to overload it in my class but i have no clue how to call it.
struct B { int a; };
struct A
{
typedef int (A::*a_func)(void);
B *p;
int a,b,c;
A() { a=0; }
A(int ... | The overloaded ->* operator is a binary operator (while .* is not overloadable). It is interpreted as an ordinary binary operator, so in you original case in order to call that operator you have to do something like
A a;
B* p = a->*2; // calls A::operator->*(int)
What you read in the Piotr's answer applies to the buil... |
1,779,722 | 1,779,754 | (c)make - resursive compile | Let's assume I have directories like:
dir1
main.cpp
dir2
abc.cpp
dir3
def.cpp
dir4
ghi.cpp
jkl.cpp
And let's assume that main.cpp includes dir2/abc.cpp and dir3/def.cpp, def.cpp includes dir4/ghi.cpp and dir4/jkl.cpp.
My question is, how can I have one Makef... | For makefile, dir1/Makefile should:
declare that main.o dependends on dir2/abc.o and dir3/def.o
declare how to create dir2/abc.o and dir3/def.o
As for cmake it detects such dependencies "automatically" (binary depended on dir2/abc.o and dir3/def.o), so virually you don't need care about it.
|
1,779,812 | 1,779,821 | Strange "type class::method() : stuff " syntax C++ | While reading some stuff on the pImpl idiom I found something like this:
MyClass::MyClass() : pimpl_( new MyClassImp() )
First: What does it mean?
Second: What is the syntax?
Sorry for being such a noob.
| This defines the constructor for MyClass.
The syntax is that of a constructor definition with an initialization list (I assume there is a set of braces following this that define the body of the constructor).
The member pimpl_ of MyClass is being initialized as a pointer to a new object of type MyClassImp. It's almost... |
1,779,974 | 1,780,040 | C++ Templates vs. Aggregation | Consider the following piece of code:
class B {
private:
// some data members
public:
friend bool operator==(const B&,const B&);
friend ostream& operator<<(ostream&,const B&);
// some other methods
};
template <typename T=B>
class A {
private:
// some data members
vector<vector<T> > vvlis... | It happens automatically.
If your code calls the operators == and <<, then the code simply won't compile if the class is passed a type that doesn't define these operators.
It is essentially duck-typing. If it looks like a duck, and quacks like a duck, then it is a duck. It doesn't matter whether it implements an IDuck ... |
1,780,024 | 1,787,312 | Visual C++ Team Test problems | I am trying to get some unit tests for native C++ running with Visual Studio Test Suite. I have just a single, simple class named "Shape". I followed a tutorial and did the following steps:
Created a "ref class" wrapper called "MShape" for the native class I want to test
Changed configuration type to .dll
Changed CLR ... | I've just set up a simple test test using MS VS Test and I could get it to run. Here is the project:
http://www.somethingorothersoft.com/TestTest.zip
I guess whatever problem you having is to do with the definition of MShape.
Alternatively, you could just test your unmanaged code directly inside tests. You will need to... |
1,780,105 | 1,781,411 | QTimer & Select use. Need to get auction time working | Currently I am having issues with QTimer. I am trying to make each "Product" have a timer and so it will let my "Handler" know that the auction time of the product has ended. The problem that I am having is that from my test, it doesn't seem to print "Timer started".
This is part of my socket programming project. I use... | Keep in mind that Qt's event loop is single threaded: If you are blocking in select() inside the main thread, then Qt's event loop can't run until select() returns, and so any pending QTimer timeout events won't be executed. Possible solutions: instead of blocking in select(), use Qt's QSocket class (etc) to impleme... |
1,780,186 | 1,780,197 | include file error in C++ | Problem fixed! Thanks a lot for the constructive suggestions!
I am unable to figure out what is the mistake in the following code. Is there something wrong with the way I am doing includes?
// This is utils.h
#ifndef UTILS_H
#define UTILS_H
#include <iostream>
#include <fstream>
#include <stack>
#include <queue>
#incl... | Those types (pair, stack, queue, vector, etc.) are in the std namespace. You either need to add using namespace std; at the top of your file (generally after all of the standard library includes) or fully qualify the type names by adding std:: in front of them.
Generally, it's better practice to fully qualify the type... |
1,780,256 | 1,780,696 | Boost::Random and Enumerated Types | Right now I'm generating a random enumerator using boost's random library. Basically I'm using an implicit conversion to specify the random generator's distribution, getting a random number, and then casting that back to the enumerated type.
Ex: (minColor and maxColor are parameters of the enumerated type)
boost::mt199... | Although it would make sense with C++0xs strongly typed enums, what you wan't isn't in general possible.
Enumeration terminology distinguishes the enumeration type and its underlying type which holds the enumeration values.
The standard mainly requires the underlying type to be big enough to hold all values, to not be ... |
1,780,351 | 1,780,586 | Linking error in C++ | Problem fixed. Thanks a lot!
I am having the following error in the code shown below:
Error is as follows:
$ g++ main.cpp Neighbor.cpp Graph.cpp
/tmp/ccclDcUN.o: In function main':
main.cpp:(.text+0xc1): undefined reference toGraph::add(int, Neighbor&)'
main.cpp:(.text+0xd3): undefined reference to `Graph::add(int, Nei... | You need to have the definition of Graph's functions (add and remove) in the .h file so that the linker can find it.
I try to think of templates like envelopes. It's nonsensical to send it (compile) before you put in a letter (defined type). Seeing as cpp files are what is compiled, it makes sense that there shouldn't ... |
1,780,536 | 1,780,604 | setting strings in gdb | c++:
int main()
{
string a = "a";
... ...
}
when i debug in gdb:
(gdb) set var a = "ok"
Invalid cast
I run the program and pause at a break point after string a has been initialized. I'm trying to set its value, but it complains about invalid cast. What's the proper syntax for this?
| You can do this:
call a.assign("ok")
This way, gdb knows right away that it needs to call a function (rather than what you tried using operator=), it knows what function to call (std::string::assign), and it doesn't need to convert types at all (since there's an overload of assign which matches exactly).
|
1,780,695 | 1,780,759 | Is is better to do const pass by references over non-const pass by references? | I came across this.
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Reference_Arguments#Reference_Arguments
According to the style guide, only const references are allowed as parameters. (That's what I understood)
Although, I don't seem to like that approach.
Comments?
| Here are a couple of rules of thumb that can be useful when deciding between your options:
If you don't need to modify the object being passed into the function, consider whether the size of the object is less than or equal to the size of a pointer. If so, pass by value; otherwise, pass by const reference.
If you do n... |
1,780,851 | 1,780,864 | Is it possible to deallocate a statically defined array? | Can you release the memory of an array defined with static allocation?
| No, it is not possible to de-allocate statically allocated memory.
Depending on the language (for example C/C++, using pointers) you may be able to use the memory held by this array for other purposes, but doing so will only re-use the memory; memory won't be released per-se.
This said, this idea of reusing static memo... |
1,780,876 | 1,780,891 | How to read unsigned short from file? | I have a bitmap image that I am parsing and I need to be able to open the file and store the first unsigned short.
I tried to accomplish this using FILE and fscanf() but fscanf() always fails and returns 0 (number of items successfully read).
FILE *pFile = fopen ( fileName->c_str() , "r" );
if ( pFile == NULL )
{
... | Don't use the formatted functions like *scanf; they expect character representations of the data, the complement of the *printf functions which translate values into character representations.
unsigned val;
f = fopen (filename, "rb");
if (fread (&val, 1, sizeof (val), f) != sizeof (val))
// error
The biggest cavea... |
1,780,933 | 1,780,947 | Parameters Naming for Constructor | In Java, usually, I can have my constructor's parameters same name as member variables.
public A(int x)
{
this.x = x;
}
private int x;
In C++, I can't. Usually, I have to do it this way.
public:
A(int x_) : x(x_)
{
}
private:
int x;
Is there any better way? As the constructor parameters name lo... | In C++, you can, if you want:
struct A {
int x;
A(int x) : x(x) {
foo(this->x);
// if you want the member instead of the parameter here
}
};
Though I also commonly use stylistic names for members (e.g. _x), I do it for non-public members. If x is public as in this example, I would do it like this, and l... |
1,780,969 | 1,781,130 | std::copy problem when reading matrix from file | I dont know why the entire matrix gets stored in the first row itself. The loop does actually get called N times if there are N rows.
and this is matrix.dat
5
1 2 3
1 2 0 100
3 4 0
5 6 -1
0 9 10 11
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
int main() {
std::vector<std::vector<... | #include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
int main()
{
std::vector< std::vector< int > > matrix;
std::ifstream infile( "matrix.dat" );
std::string s;
while( std::getline( infile, s ) )
{
std::string token;
std::vector< int > tok... |
1,781,137 | 1,781,206 | C++ Preprocessor metaprogramming: obtaining an unique value? | I'm exploiting the behavior of the constructors of C++ global variables to run code at startup in a simple manner. It's a very easy concept but a little difficult to explain so let me just paste the code:
struct _LuaVariableRegistration
{
template<class T>
_LuaVariableRegistration(const char* lua_name, const T&... | You need to add an extra layer of macros to make the preprocessor do the right thing:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define LUA_GLOBAL(lua_name, c_name) ... TOKENPASTE2(_luaGlobal, __LINE__) ...
Some compilers also support the __COUNTER__ macro, which expands to a new, uni... |
1,781,182 | 1,781,190 | NULL Pointer Problem? | void Insert(AVLnode * & root, string X)
{
if ( root == NULL)
{
root = GetNode(X);
}
else if ( root->info > X )
{
Insert(root->left,X);
if ( height(root->left) - height(root->right) == 2 )
if ( X < root->left->info )
RotateRR(root);
else... | The problem is in the AVLnode* Dic; statement of main(). You are sending an uninitialized pointer to insert() from main(). It contains garbage values. Initialize it to NULL
|
1,781,312 | 1,781,360 | Question about file transfer for socket programming | Is there a good method on how to transfer a file from say... a client to a server?
Probably just images, but my professor was asking for any type of files.
I've looked around and am a little confused as to the general idea.
So if we have a large file, we can split that file into segments...? Then send each segment off ... | If you are using TCP:
You are right, there is no way to "know" how much data you will be receiving. This gives you a few options:
1) Before transmitting the image data, first send the number of bytes to be expected. So your first 4 bytes might be the 4-byte integer "4096". Then your client can read the first 4 bytes, "... |
1,781,417 | 1,781,422 | Get the number of elements in a pointer to a char array in C++ | I realise this is an incredibly noob question, but I've googled for it and can't seem to find an answer (probably because I've worded the question wrong... feel free to fix if I have)
So I have this code:
int main(int argc, char* argv[])
{
puts(argv[1]);
return 0;
}
It works fine if I've passed a parameter to ... | That's what argc is for. It holds the number of elements in argv. Try to compile and run this:
#include <stdio.h>
int main(int argc, char* argv[]) {
int i;
if (argc < 2) {
printf ("No arguments.\n");
} else {
printf ("Arguments:\n");
for (i = 1; i < argc; i++) {
printf ("... |
1,781,616 | 2,308,352 | C++/WinInet Change Proxy Settings Windows 7 | [Disclaimer: this is a Windows 7 specific issue as far as I can tell]
I've got a block of code that changes the proxy settings in the Windows registry, then proceeds to call the WinInet API with the following:
InternetSetOption(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0);
InternetSetOption(NULL, INTERNET_OPTION_RE... | FWIW my original problem was not using the entire WinInet API to handle the proxy settings. The answer has been staring me in the face from the beginning... A final solution might look something like:
LPWSTR proxyName;
if (on) {
proxyName = L"http=[IPADDRESS:PORT];https=[IPADDRESS:PORT]";
} else {
proxyName ... |
1,781,722 | 1,785,687 | Can't lua_resume after async_wait? | I have some lua script that have some long running task like getting a web page so I make it yield then the C code handle get page job async, so the thread free to do other job and after a specify time it check back to see is the get page job finished , if so then resume the script. the problem is the thread can't resu... | Sorry never mind this question, lua_resume return 2 mean error but script work just fine, asio get page work fine too, and I tracked down the line that respond for fail of lua_resume :
httpinfo.header.append(buffer, (HeaderEndIndex-buffer+2) );
if I comment that line lua_resume work as expected it return 0 mean script ... |
1,781,763 | 1,781,776 | what exactly is dynamic casting in c++ | can anyone tell what exactly is dynamic casting means in c++.
where exactly can we use this dynamic casting?
this was asked to me in the interview and i went blank for this question:).
| Try to use the search first
old answer
|
1,781,777 | 1,782,002 | How to write mp3 frames from PCM data (C/C++)? | How to write mp3 frames (not full mp3 files with ID3 etc) from PCM data?
I have something like PCM data (for ex 100mb) I want to create an array of mp3 frames from that data. How to perform such operation? (for ex with lame or any other opensource encoder)
What do I need:
Open Source Libs for encoding.
Tutorials and b... | You should be able to use LAME. It has a -t command line switch that turns off the INFO header in the output (otherwise present in frame 0). If that still leaves too much bookkeeping data, you should be able to write a separate tool to strip that away.
|
1,781,802 | 1,781,817 | Order of destruction for Array of Objects | class MyClass
{
};
void foo
{
MyClass arr[10];
}
I want to know the order of destruction of array objects when function returns.
I read it More Effective C++ about it and it says that destructor are invoked in reverse
order to that of constructor order as follows:
for(int i = 9 ; i >= 0 ;i--)
{
arr[i].MyCla... | That's continuation of reverse order of destructor invokation filosophy of C++. When stack-allocated objects are destroyed it is done in reverse order to facilitate RAII. Although that is not really necessary for array elements (they are all constructed with the default constructors and any order of construction/destru... |
1,781,818 | 1,781,971 | Set dirty dot in mac window using Qt | screen shot http://img14.imageshack.us/img14/2338/200911231633.png
Is there a way to set the dirty dot (as shown in the screenshot) using Qt 4.5/4.6?
| Use the QWidget::setModified()
|
1,781,906 | 1,782,153 | CoCreateInstance returning E_NOINTERFACE even though interface is found | I have a COM class CMyCOMServer implementing IMyInterface in one application, both with correct GUIDs. CMyCOMServer::QueryInterface will return S_OK (and cast itself to the right type) if IUnknown or IMyInterface is requested, otherwise it returns E_NOINTERFACE.
In another app on the same PC, I call:
HRESULT hr = ::CoC... | If your COM server is running in a different process, or a different apartment in the same process, COM needs to know how to package and transmit parameters when you make calls to your interface. This process is called "marshaling".
If you define a custom interface, you need to implement marshaling for it using one of... |
1,782,035 | 1,782,082 | Can I have a compile time constant instance of a class (as a member) in C++? | In C++, say I have a class Thing, I'd like it to include a const member of that type, something like:
class Thing
{
public:
Thing();
private:
static const Thing THING;
};
But I don't think this works as above. How can I do this?
| The following little program compiles and links using GCC 3.4.5 (MinGW):
class Thing
{
public:
Thing();
private:
static const Thing THING;
};
Thing::Thing()
{}
// We must instantiate the static variable somewhere, like inside 'Thing.cpp'
const Thing Thing::THING = Thing();
int main(int argc, char* argv[])
{ ... |
1,782,068 | 1,789,271 | Compile Combination of qtwinmigrate + qtpropertybrowser Under VC++ 2008 | I need to display a property browser under a MFC app.
I try to combine and compile the solution for the two
http://qt.nokia.com/products/appdev/add-on-products/catalog/4/Windows/qtwinmigrate/
http://qt.nokia.com/products/appdev/add-on-products/catalog/4/Widgets/qtpropertybrowser/
I am using VC2009, QT 2009.04 with Visu... | 1) Under Visual Studio 2008, go to Qt -> Open Qt Project File (.pro), open
qtpropertybrowser.pro
2) Go to "simple" Properties, under Build Events -> Pre-Build Event, enter the
following commands :
moc ..\..\src\qttreepropertybrowser.cpp > ..\..\src\qttreepropertybrowser.moc
moc ..\..\src\qtpropertymanager.cpp > ..\..\s... |
1,782,109 | 1,782,142 | MSN Messenger/Growl Style Alerts in Windows C++ | Does anyone know of any C++ Libraries which I can easily integrate in a project to allow me to show MSN Messenger/Outlook/Growl style toast popups?
Tried having a look and found lots of Visual Basic controls etc but nothing for C++ so far.
| You might wanna a look at Customizable Alert Window by Marius Bancila.
|
1,782,138 | 1,782,192 | A template question: Can compiler deduce template type in static method | I have the following setup:
A templated class SpecialModel:
template<typename A, typename B>
class SpecialModel<A, B> {
};
A templated Worker, working on some kind of Model:
template<typename M>
class Worker<M> {
Worker(M& model);
void work();
};
And a specialization of Worker for SpecialModel:
template<ty... | If Train is a templated class, as it appears to be, the compiler cannot deduce class templates from static method template arguments.
If Train::train is a static method, why is your class Train templated? Method train cannot access any member variables anyway. You could probably make train a free function:
template<cla... |
1,782,337 | 2,057,662 | Implementing and inheriting from C++ classes in Lua using SWIG | Would it be possible using Lua and SWIG and say an IInterface class, to implement that interface and instantiate it all within Lua? If so how would it be done?
| Store the table in a c++ class by holding a pointer to the lua state, and the reference returned for the table as specified using this API:
http://www.lua.org/pil/27.3.2.html
Then when a method on the wrapper class is called, push the referenced object onto the stack and do the necessary function call
|
1,782,683 | 1,782,691 | Is there any standard way to load parameters from a file in C++ on Linux? | Imaging that a program needs to know quite a lot of parameters to do its tasks properly, such as 'Port = 2323' this kind of things.
now I want to save these parameters in a plain text file, similar to Unix' system variables such as users and groups.
Is there any standard way/libraries that can help me to do this? Does ... | Boost.Program_options library. Is this you are looking for?
The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.
|
1,783,350 | 1,783,366 | C++ copy constructor invocation | As far as i know, a copy constructor is invoked in the following scenarios :
1) Pass by value
2) Return by value
3) When you create and initialize a new object with an existing object
Here's the program :
#include <iostream>
using namespace std;
class Example
{
public:
Example()
{
... | A copy constructor might not be invoked when you return by value. Some compilers use return value optimization feature.
Read about "Return Value Optimization"
|
1,783,465 | 1,783,509 | Why must I put a semicolon at the end of class declaration in C++? | In a C++ class declaration:
class Thing
{
...
};
why must I include the semicolon?
| The full syntax is, essentially,
class NAME { constituents } instances ;
where "constituents" is the sequence of class elements and methods, and "instances" is a comma-separated list of instances of the class (i.e., objects).
Example:
class FOO {
int bar;
int baz;
} waldo;
declares both the class FOO and an object... |
1,783,652 | 1,783,672 | What is the best autocomplete/suggest algorithm,datastructure [C++/C] | We see Google, Firefox some AJAX pages show up a list of probable items while user types characters.
Can someone give a good algorithm, data structure for implementing autocomplete?
| A trie is a data structure that can be used to quickly find words that match a prefix.
Edit: Here's an example showing how to use one to implement autocomplete http://rmandvikar.blogspot.com/2008/10/trie-examples.html
Here's a comparison of 3 different auto-complete implementations (though it's in Java not C++).
* In... |
1,783,762 | 1,783,812 | typedef _W64 unsigned int UINT_PTR, *PUINT_PTR; | What does exactly this mean?
typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;
Does this mean that *PUINT_PTR is a pointer (obviously) and UINT_PTR is NOT a pointer? If so, why is it called UINT_PTR ? (which I would read as unsigned int pointer, or pointer to unsigned int)
Thanks
| Yes, this means that PUINT_PTR is a pointer and UINT_PTR is not a pointer. It's a little confusing, but a UINT_PTR (as well as the more standardized uintptr_t) is defined to be an unsigned integer that is guaranteed to be large enough to hold a pointer value. It's typically used for tricky code where pointers are put... |
1,783,822 | 8,914,410 | Technical reasons behind formatting when incrementing by 1 in a 'for' loop? | All over the web, code samples have for loops which look like this:
for(int i = 0; i < 5; i++)
while I used the following format:
for(int i = 0; i != 5; ++i)
I do this because I believe it to be more efficient, but does this really matter in most cases?
| I have decided to list the most informative answers as this question is getting a little crowded.
DenverCoder8's bench marking clearly deserves some recognition as well as the compiled versions of the loops by Lucas. Tim Gee has shown the differences between pre & post increment while User377178 has highlighted some ... |
1,783,849 | 1,783,905 | What are the advantages and disadvantages of implementing classes in header files? | I love the concept of DRY (don't repeat yourself [oops]), yet C++'s concept of header files goes against this rule of programming. Is there any drawback to defining a class member entirely in the header? If it's right to do for templates, why not for normal classes? I have some ideas for drawbacks and benefits, but wha... | Possible advantages of putting everything in header files:
Less redundancy (which leads to easier changes, easier refactoring, etc.)
May give compiler/linker better opportunities for optimization
Often easier to incorporate into an existing project
Possible disadvantages of putting everything in header files:
Longer... |
1,783,883 | 1,784,224 | Special interaction between derived objects (i.e. mutiple dispatch) | So, I have a list of base class pointers:
list<Base*> stuff;
Then, at some point one of the objects will look through all other objects.
Base * obj = ...; // A pointer from the 'stuff'-list.
for (list<Base*>::iterator it = stuff.begin(); it != stuff.end(); it++)
{
if (obj == *it)
continue;
// Problem ... | If you can, grab a copy of "More Effective C++", and have a look at item #31 which is about implementing multiple dispatch, which is basically what you're looking for here. Meyers discusses several approaches to the problem and their various trade-offs. (He even uses a game as an example.)
Perhaps the best advice he gi... |
1,784,573 | 1,784,845 | iterator for 2d vector | How to create iterator/s for 2d vector (a vector of vectors)?
| Although your question is not very clear, I'm going to assume you mean a 2D vector to mean a vector of vectors:
vector< vector<int> > vvi;
Then you need to use two iterators to traverse it, the first the iterator of the "rows", the second the iterators of the "columns" in that "row":
//assuming you have a "2D" vector ... |
1,784,767 | 1,784,778 | g++ error: ‘stricmp’ was not declared in this scope (but OK for 'strcmp') | I am trying to compile the following very very simple piece of source code:
#include <cstring>
// #include <string.h>
// using namespace std;
class Helper {
public:
int cStringsAreEqual(const char *s1, const char *s2) {
return stricmp(s1, s2);
}
};
... but I am getting the following error message:
... | Try strcasecmp(). Here's the manual page for it. It is conforming to 4.4BSD and POSIX.1-2001.
|
1,785,028 | 1,785,135 | Class not registered | I'm working through "Developer's Workshop to COM and ATL 3.0" by Andrew W. Troelsen.
I'm trying to implement the lab in Chapter 3.
It shows you how to build a COM client to connect to an inprocess COM server that was developed in an earlier lab.
When I run the client, I receive the error "Class not registered" when cal... | Open a command prompt, change to your DLL's folder, and run regsvr32.exe:
cd \Users\Steven\Documents\Visual Studio 2005\Projects\CarInProcServer\release
regsvr32 CarInProcServer.dll
|
1,785,100 | 1,785,120 | Why use a pointer to a pointer to the stack when creating a push function? | I am looking at a textbook example of a linked list that implements a stack. I don't understand why using a pointer to a pointer to the stack is necessary for the push operation. See the following example:
bool push( Element **stack, void *data)
{
Element *elem = new Element;
if(!elem) return false;
elem->... | The function needs to modify the value of the Element pointer, so it needs a pointer to that pointer.
Put it another way: a function takes a pointer of something when it needs to modify that thing.
In this case, that something is a pointer itself. So the function ends up taking a pointer to a pointer.
|
1,785,416 | 1,785,427 | C++ naming: read_input() vs. readInput() | Which naming convention is more preferable in C++? The underscore method or the camelCase method?
I have coded in Java for a while and I am used to the camelCase naming conventions.
Which one is more prevalent?
Also, while defining a class, is there any preferred ordering of private/public/protected variables/methods?... | This is all very subjective, but generally for C++ I do:
camelCase for functions and variables.
PascalCase for classes.
public:
protected:
private:
In classes.
Edit: Forgot these 2:
Yes, friend at the end, typedef either at the beginning if they are used in the class, or after if they use the class (for obvious reason... |
1,785,426 | 1,785,435 | C# null coalescing operator equivalent for c++ | Is there a C++ equivalent for C# null coalescing operator? I am doing too many null checks in my code. So was looking for a way to reduce the amount of null code.
| There isn't a way to do this by default in C++, but you could write one:
in C# the ?? operator is defined as
a ?? b === (a != null ? a : b)
So, the C++ method would look like
Coalesce(a, b) // put your own types in, or make a template
{
return a != null ? a : b;
}
|
1,785,572 | 1,785,622 | Why should one bother with preprocessor directives? | This question may seem rather basic, but coming from an engineering (non computer-science) background, I was unsure about what the snippets of '#'s were in some C++ code.
A quick search led me to the concise, well-explained cplusplus tutorial page on preprocessor directives.
But why bother with the concept of preproces... | You use preprocessor directives when you need to do something outside of the scope of the actual application. For instance, you'll see preprocessing done to include or not include code based on the architecture the executable is being built for. For example:
#ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers
... |
1,785,612 | 1,785,703 | How do I pass multiple heap arrays to a new thread? | I'm trying to learn how create new threads and run them. I need to pass a few variables into the function that is run on the new thread but I can't find out how to actually pass anything to that new function/thread.
I'm following http://www.devarticles.com/c/a/Cplusplus/Multithreading-in-C/1/ but it only goes through h... | The underlying OS allows to pass only one parameter to a thread CreateThread:
HANDLE WINAPI CreateThread(
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in SIZE_T dwStackSize,
__in LPTHREAD_START_ROUTINE lpStartAddress,
__in_opt LPVOID lpParameter,
__in DWORD dwCreationFlags,
__o... |
1,785,617 | 1,785,643 | Shared Library Path as Executable Directory | I have an application that is broken into several libraries for purposes of code reuse. On Windows all I have to do is put the .dll files in the same path as the executable and it automatically finds them. On Linux (since it hardcodes the paths to things) I have to specify the environmental variable LD_LIBRARY_PATH o... | You need $ORIGIN in your RPATH, via an appropriate option to ld or other Darwin tool. See this and this.
Remember that the $ has to really end up in the path, so you need to quote or escape it in the link command line.
Update:
You can see what the linker actually put into your executable with
readelf -d /path/to/exe | ... |
1,786,066 | 1,786,108 | Questions about vector, union, and pointers in C++ | The questions I have are NOT homework questions, but I am considering using these concepts in my assignment. The context, if it helps, is like this: I need to keep track of several union instances and they belong to my own union in one of my own classes as class variables. (Note: the number of union instances is unknow... |
If the union is CopyConstructable and Assignable, then it meets the requirements for std::vector.
Yes: MyUnion* ptr = new MyUnion();
A container of pointers works in some situations, but if you want a container of owning pointers, look at Boost's ptr_* containers. However, here it appears you'd either have a contai... |
1,786,144 | 1,786,280 | C++ passing const string references in methods? | I'm trying to initialize a private variable of my Class passing a const string &aString to it as parameter.
Here's my method:
void Image::initWithTextureFile(const std::string &inTextureName)
{
Texture2D *imTexture = TEXTURE_MANAGER->createTexture(inTextureName);
if(imTexture)
{
texture = imText... | If you're outside the class scope, and cout << name compiles at all, it means you have another variable named name, and that's what's being picked up. If you want to refer to it outside the class, you'll have to come up with a way that will export it. You might, for example, have a member function like const std::str... |
1,786,661 | 1,786,691 | Semicolon after classes and structs |
Possible Duplicate:
Why must I put a semicolon at the end of class declaration in C++?
Found duplicate, vote to close please.
Why do classes and structs have to be concluded with semicolon in C++?
Like in the following code:
class myClass
{
};
struct muStruct
{
};
This syntax isn't necessary in Java or C#. Why... | This is why...
int a,b,c,d;
int main(void) {
struct y {
}; a, b, c, d;
struct x {
} a, b, c, d;
}
Two different statements, two completely different meanings, both legal C / C++, and the only difference is the ; after the struct declaration.
|
1,786,809 | 1,786,968 | Map functions of a class | Before I was trying to map my classes and namespaces, by using static calls I succeded and now I need to map the functions of my classes because they will be used dynamically.
Firstly I was thinking to hardcode in the constructor so I can assign a std:map with the string of the name of function pointing to the function... | If I understand you correctly, you want your map to store a pointer that can be used to call a member function on an instance, the value being chosen from the map at run time. I'm going to assume that this is the right thing to do, and that there isn't a simpler way to solve the same problem. Quite often when you end u... |
1,786,873 | 1,786,883 | Calculate direction vector | HI All,
How can I calculate direction vector of a line segment, defined by start point (x1, y1) and end point (x2, y2)?
Cheers.
| (x2 - x1, y2 - y1)
If you want the unit direction vector, divide each component by sqrt((x2 - x1)² + (y2 - y1)²).
|
1,786,884 | 1,786,981 | iterator dereferencing issue | if I have
list<NS*> v;
typename list<NS*>::iterator it;
for(it = v.begin();it!=v.end();++it){
cout<<**it.ns_member1<<endl; // does not compile
NS ns = **it;
cout<<ns.ns_member1<<endl; // this compiles.
}
Why so?
| Dereference (the '*') has a lower precedence than the '.' operator, so this line:
cout<<**it.ns_member1<<endl;
Works out like this:
cout << (**(it.ns_member1)) <<endl; // ERROR
I would suggest doing it like this:
cout << (*it)->ns_member1 << endl;
There is really no need to use the dereference operator twice, once f... |
1,786,887 | 1,786,954 | From Visual Studio to Vim or Emacs? | I'm starting a new job next month. I've practically lived inside Visual Studio professionally for 10 years give or take, but for this job I'll be working full time on the linux platform for the first time in my life.
During one of the interview meatings I was seated in the middle of the developer room to socialize with... | If you're ambivalent, the only correct answer is: Use what the people around you use.
|
1,786,986 | 1,786,994 | Why is my insert into std::map failing? | In my header file, I'm declaring a map like so:
std::map<LPD3DXSPRITE, LPDIRECT3DTEXTURE9> sprites;
In my C++ file, I am trying to insert like so:
sprites.insert(sprite, texture);
The types I am passing to sprites.insert are correct. Why can I not insert this way? What is the proper way to insert? When I do this, ... | You need to wrap your key and value in an std::pair object:
sprites.insert(std::make_pair(sprite, texture));
This is because std::map is a Pair Associative Container. The value_type of std::map<K,V> is std::pair<const K,V>.
|
1,787,174 | 1,787,195 | How does C++ handle multiple source files? | I'm studying C++ right now, coming from a background in Python, and I'm having some trouble understanding how C++ handles multiple source files. In Python, the import statement first checks the current working directory for the module you're trying to import and then it checks the directories in sys.path. In C++, where... | There are two include variants:
#include "path-spec"
#include <path-spec>
Quote notation:
This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file.
The bracket ... |
1,787,246 | 1,787,460 | How to best save XML files | I have a bunch of classes that each read in their values from an XML file using TinyXML.
I've done this so everything is in memory, and my user is using the app and making changes. If the user presses Save, I need to iterate through my objects and call the Save() function which writes out the XML file. Should I rebui... | I would dispose of the reading handles once you have read the XML input.
To write them back out you would typically have a writeXML() method in the parent or main document type object an then have that call a writeXML() method in each object in your design.
ps. It's not unusual to have different XML reading and wr... |
1,787,293 | 1,787,318 | Get a reverse iterator from a forward iterator without knowing the value type | I'm trying to implement some STL-style sorting algorithms. The prototype for std::sort looks something like this (from cplusplus.com):
template <class RandomAccessIterator>
void sort ( RandomAccessIterator first, RandomAccessIterator last );
The function is generally called like this (although the container type can v... | The STL has std::reverse_iterator<Iterator>:
template <class RandomAccessIterator>
void mySort(RandomAccessIterator first, RandomAccessIterator last)
{
typedef std::reverse_iterator<RandomAccessIterator> RIter;
RIter riter(last);
RIter rend(first);
for ( ; riter != rend; ++riter) {
// Do stuff
}
}
An im... |
1,787,548 | 1,787,566 | How many threads to create? | I am just learning how to write mutithreaded programs right now and I have a hypothetical question about how many threads are optimal for a program.
Let me describe 2 scenarios.
The first scenario is that i have a program that is easily multi threaded but each thread is going to be doing a lot of work (execution times... | Scenario #1: Make n threads, where 'n' is the number of CPU cores
Scenario #2: The same, but instead of creating and killing the threads all the time, use a Workitem / Thread Pool based approach, like the .NET Parallel Framework does.
Edit: This is a good article that covers #2 - http://msdn.microsoft.com/en-us/magazin... |
1,787,599 | 1,787,623 | Int32 not declared in this scope | I have the following code:
//Comp454 program 2
#include <iostream>
#include <string>
#include <fstream> // file I/O support
#include <cstdlib> // support for exit()
const int SIZE = 60;
int main()
{
using namespace std;
string states;
int numStates = 0, i = 0, stateVar = 0;
string line;
char filename[SIZE];
ifst... | Try using atoi() instead. States is a std::string so you will need to say:
numStates = atoi( states.c_str() );
|
1,787,601 | 1,787,615 | HTTP server, after a connection is accepted I get -1 returned from recv() | I have to implement an HTTP server for a class in C++, but after a connection is accepted, recv() just returns -1. How can I fix this? I posted my code below.
int main( int argc, char* argv[] )
{
// Interpret the command line arguments
unsigned short port = 8080;
char* base_directory = NULL;
base_directory = ge... | you are recv'ing on the wrong socket.
You are using tcp_sock(which is your listening socket), not the socket returned by the accept call.
Change it to acc_tcp_sock and you should be good to go:
recv_len = recv( acc_tcp_sock, recv_buffer + bytes_recv,
3000 - bytes_recv, 0 );
|
1,787,604 | 1,787,609 | printf((char *) i); runtime error? (i as integer) | In a for loop, I am trying to use printf to print the current i value. This line: printf((char *) i); is giving me runtime errors. Why is this?!
Below is a quick fizzbuzz solution that is doing this:
void FizzBuzz()
{
for (int i = 0; i < 20; i++)
{
printf((char *)i);
if ((i % 3 == 0) && (i % 5... | Because that's not how printf works. You want this instead:
printf("%d\n", i);
Or even better,
std::cout << i;
|
1,787,643 | 1,787,671 | Is this a standard C++ code? | The following simple piece of code, compiles with VC2008 but g++ rejects the code:
#include <iostream>
class myclass
{
protected:
void print() { std::cout << "myclass::print();"; }
};
struct access : private myclass
{
static void access_print(myclass& object)
{
// g++ and Comeau reject this line b... | I believe g++ and comeau are correct. The specifier for a protected member must be of type "access" or derived, so I believe the code:
void (myclass::*function) () = &access::print;
would compile.
I believe this is because of 11.5.1:
... If the access [ed. to a protected
member ] is to form a pointer to
member, t... |
1,787,752 | 1,787,870 | Is there a g++ equivalent to Visual Studio's __declspec(novtable)? | Is there a g++ equivalent to Visual Studio's __declspec(novtable) argument?
Basically, in a pure virtual base class the __declspec(novtable) argument can be used to suppress the creation of a vtable for the base class as well as vtable initialization/deinitialization code in the contstructor/destructor respectively. E... | I don't think there is one -- if there was, it would be listed under the type attributes page of the GCC manual. GCC uses type attributes to add extra annotations to types (such as alignment and padding), but there is no type attribute equivalent to __declspc(novtable) listed there.
I also don't see any compiler flag ... |
1,787,822 | 1,787,830 | Why aren't include guards or pragma once working? | I'm compiling some code that relies on include guards to prevent multiple definitions of objects and functions, but Visual Studio 2008 is giving me link errors that there are multiple definitions. I don't understand why because I've used code very similar to this before and it hasn't caused problems. I must be doing so... | If they are linker errors, the most likely cause is probably non-inline functions defined in the header.
If you have a non-inline function in a header that is included in more than one source file, it will be defined in each of those source files ("translation units"), thus the function will be defined more than once... |
1,787,856 | 1,787,922 | What is the element value in an uninitialized vector? | If I create a vector like vector<myClass> v(10);
what is the default value of each element?
Also, what if it is a vector<myUnion> v(10) ?
| The constructor of std::vector<> that you are using when you declare your vector as
vector<myClass> v(10);
actually has more than one parameter. It has three parameters: initial size (that you specified as 10), the initial value for new elements and the allocator value.
explicit vector(size_type n, const T& value = T... |
1,787,875 | 1,787,927 | Use of "extern" storage class specifier in C | How does the following example usage of extern specifer behave.
We have a global variable int x both in files one.c and two.c
We want to use these in three.c so have declared this variable in three.c as
extern int x;
What would happen when we compile and link these files?
My answer is: compilation of all these file... | By default, global variables have external linkage, which means that they can be used by other source files (or "translation units"). If you instead declare your global variables with the static keyword, they will have internal linkage, meaning they will not be usable by other source files.
For variables with external... |
1,787,909 | 1,787,943 | Pthreads C++ compilation error | I'm getting error "undefined reference to `pthread_attr_init'", even though that should be in pthread.h. This is in a UNIX environment that should be set up for Pthreads. Also, is a void* a good way to point to the current matrix? Here's my code, any ideas?
#include <cstdlib>
#include <iostream>
#include <sstream>
#inc... | It will depend on your platform, but I would try adding -lpthread to your link command as that's what is required in Linux and a few others. Your program compiles fine here as g++ foo.cc -lpthread.
|
1,787,966 | 1,788,037 | what is the capacity of an empty vector? | Looks like a stupid question. But comment to my answer to one of the SO question made me to think again.
[ comment says, capacity need not be zero for empty vector]
By default my answer would be 0 as there are no elements inside vector. It makes sense to keep the capacity as 0 and on the first allocation it can be inc... | C++ Standard 23.2.4.2 only says that vector::capacity is
The total number of elements that the vector can hold without requiring reallocation.
That means that the actual value is fully implementation specific.
|
1,788,035 | 1,788,066 | Sharing methods between two implementations of a virtual base class in C++ | I have a virtual base class and two classes that implement the various methods. The two classes have the same functionality for one of the methods. Is there away I can share the implementation between the two classes to eliminate redundant code? I tried making the first class a parent of the second class in addition to... | Say, A is the base class, and B and C are classes that inherit from the base class. The method whose logic is shared between B and C is called SomeMethod. One of the following should do the trick, regardless of your use case:
Take the logic for B::SomeMethod and C::SomeMethod and copy-and-paste it into A::SomeMethod... |
1,788,043 | 1,788,057 | Why do I see 64-bit pointers in C++ on my 32-bit Mac OS X system? | So I've read a lot of related posts on SO and elsewhere such as:
Is the sizeof(some pointer) always equal to four?
It makes total sense to me that on a 32-bit system I would expect 4-byte pointers and on a 64-bit system I would expect 8-byte pointers. So I'm running this code:
int main()
{
cout << "sizeof(int) = " <... | You're running a 32-bit kernel, but you're compiling the code into a 64-bit executable. Both 32- and 64-bit code can run in OS X, regardless of which kernel is in use.
If you want to compile the code into a 32-bit executable, pass the -arch i386 flag to gcc. The corresponding flag for 64-bit is -arch x86_64, but it i... |
1,788,259 | 1,788,295 | Crash when utilising a std:map | In my SDL program, I am using a map construct to simulate an "infinite" array of objects within a certain class. The code manages to compile fine, but when I run the program, as soon as one of the functions using the maps is trigger, the program crashes, returning a value of 3.
So, here's exactly what I'm doing:
class ... | Maybe you are calling the function from an uninitialized pointer, like this:
MyClass *obj;
obj->MyFunction();
|
1,788,550 | 1,804,259 | Should the conditional operator evaluate all arguments? | When writing this:
1: inline double f( double arg ) {
2: return arg == 0.0 ? 0.0 : 1./arg;
3: }
4: const double d = f( 0.0 );
The microsoft visual studio 2005 64-bit compiler came with
line 4: warning C4723: potential divide by 0
While you and I can clearly see that a div-by-zero is never going to happen...
Or i... | It's an obvious bug, beyond doubt.
The intent of the warning is NOT to warn about all divisions in a program. That would be far too noisy in any reasonable program. Instead, the intent is to warn you when you need to check an argument. In this case, you did check the argument. Hence, the compiler should have noted that... |
1,788,659 | 1,788,682 | Seemingly basic C++ question | Alright, so this is annoying the hell out of me and I'm sure its a simple thing to do. Basically, I'm working with an open source C++ client called POCO to make a email client for a class...
Basically, I have a pop3 client object that retrieves emails from my email server, and then puts the emails in an object called M... | You can either say
const std::string& s = contentTransferEncodingToString(ENCODING_7BIT)
or
const std::string& s = contentTransferEncodingToString(ContentTransferEncoding::ENCODING_7BIT)
|
1,788,702 | 1,788,775 | Visual Studio fails to display some watched expressions | In Visual Studio, most of my objects and variables cannot be resolved during a debugging session for various reasons. This means I cannot inspect or watch objects or their invoke their functions making it extremely difficult to debug my code because most of my expressions simply won't work. Some typical errors I get ... | The errors you have are due to limitations in the debugger, there are not bugs as Daniel implies.
The watch window cannot call overloaded operators.
If you have e.g. a std::vector<int> vecSomething you cannot put vecSomething[0] into the watch window, because std::vector<int>::operator[] is an overloaded operator. Con... |
1,789,035 | 1,789,150 | Sending message to different thread | Is there any API to send message to a thread?
Basically I have only threadId available and I want to send a custom message to that thread.
| PostThreadMessage. Not very reliable though.
See The Old New Thing blog here and here for details on why. Basically modal message loops make a mess of the whole idea. Since a message posted to a thread has no window handle, calling DispatchMessage will throw the message away. Any modal loop you run - directly or indire... |
1,789,063 | 1,792,079 | not able to install hooks for all threads in a process | I am hooking keyboard in application . Requirement is to hook keyboard in all threads in the process.
I used SetWindowsHookEx API
SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)::KeyboardHookProc, hInst, 0);
The hook is created for all the threads in process.
This works fine until calling thread exists .As soon as calling... | This fine print in the SDK docs for LowLevelKeyboardProc is crucial:
This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop.
In other words, you must keep the... |
1,789,195 | 1,789,211 | How to debug a program that is terminating in an unhandled exception? | I am programming in C++ on Linux platform.
My program terminates with this (unhandled???) exception:
"terminate called after throwing an instance of 'long'"
Aborted
The code that is throwing the exception is inside try-catch block, then why should this happen??
The exception is thrown while returning from a function.
I... | you are probably catching the wrong exception type
use
catch(long)
or
catch(...)
|
1,789,320 | 1,789,655 | How to find out if a thread has message queue? | Is there any way to find out from threadId , if a thread has message queue or not?
Basically there are some windows api which only work if a thread has message queue.window
| You can use PostThreadMessage with the ID of the thread. If PostThreadMessage returns false and GetLastError returns ERROR_INVALID_THREAD_ID, the thread ID is invalid or the thread does not have a message queue.
More information http://msdn.microsoft.com/en-us/library/ms644946(VS.85).aspx
|
1,789,341 | 1,789,356 | Can we use pthread instead of NSThread in iPhone apps | Well I have an application that uses both Objective C & c++ but for portability reasons I have tried to use c++ as much as possible.... Now I am confronted with some problem that requires threads I was thinking of using pthread instead of NSThread... is it Okay to use pthread? Will Apple punish me for using it by rejec... | NSThread is built around pthread anyway
I can't see any reason why using pthread would lead to rejection from Apple's part
|
1,789,421 | 1,790,762 | NULL pointer is the same as deallocating it? | I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?
For instance:
A = new MyClass();
{...do something in the meantime...}
A = NULL;
The space is still allocated, but there is no reference to it. Will that space be freed l... | A = new MyClass();
{...do something in the meantime...}
A = NULL;
The way I keep track of it is that there are two separate objects. Somewhere on the heap, a MyClass instance is allocated by new. And on the stack, there is a pointer named A.
A is just a pointer, there is nothing magical about out, and it doesn't hav... |
1,789,768 | 1,790,124 | Can I change dll-interface without recompilation exe-file? | I have an abstract class in my DLL.
class Base {
virtual char * First() = 0;
virtual char * Second() = 0;
virtual char * Third() = 0;
};
This dinamic library and this interface are used for a long time.
There is my mistake in my code. Now I want to change this interface
class Base {
virtual const char * First(... | It "shouldn't" work, but you never know your luck.
Because of overloading, char *First() and const char *First() const are different functions. You could have both in the same class. So any name-mangling scheme has to map them to different names, which obviously is a problem when it comes to binding.
But, these are vir... |
1,789,883 | 1,790,061 | Grab exclusively/release mouse in application (Windows, C++) | I have lost many hours trying to grab exclusively the mouse in my application and re-releasing it.
Right now, I am grabbing it correctly: the mouse cursor disappears from screen and I can read its properties fine.
However, I can't release it correctly! The mouse cursor reappears on screen but no other application is re... | Possibly it because of this
http://doc.51windows.net/Directx9_SDK/?url=/directx9_sdk/input/ref/ifaces/idirectinputdevice9/setcooperativelevel.htm
""An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messa... |
1,790,084 | 1,790,103 | std::string a container | Is std::string a container class in standard c++ library, restricted to hold only char elements?
| It's a typedef of std::basic_string<char>, actually. std::basic_string is a container class specifically designed for string operations. This container can be used for wide characters (wchar_t) as well; for that case its typedef would be wstring.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.