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,364,603 | 1,364,631 | Performance of comparisons in C++ ( foo >= 0 vs. foo != 0 ) | I've been working on a piece of code recently where performance is very important, and essentially I have the following situation:
int len = some_very_big_number;
int counter = some_rather_small_number;
for( int i = len; i >= 0; --i ){
while( counter > 0 && costly other stuff here ){
/* do stuff */
... | Do you think that what will solve your problem! :D
if(x >= 0)
00CA1011 cmp dword ptr [esp],0
00CA1015 jl main+2Ch (0CA102Ch) <----
...
if(x != 0)
00CA1026 cmp dword ptr [esp],0
00CA102A je main+3Bh (0CA103Bh) <----
|
1,364,793 | 1,364,815 | Initializing arrays in C++ | I'm trying to initialize the last element in the array
int grades[10];
to grade 7 but it doesn't seem to work
I'm using C++ btw
| If you want to initialize them all at definition:
int grades[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 };
If you want to initialize after:
int grades[10];
grades[9] = 7;
But, be aware that grades 0..8 will still be uninitialized, and will likely be junk values.
|
1,364,837 | 1,364,878 | Why doesn't this C++ template code compile? | Does anyone know why this will not compile? I've tried both VS 2008 and GCC 4.something and both spit out errors. It doesn't matter whether or not I'm referencing "ThisFunctionDoesNotCompile()".
I can workaround this by just passing 'InternalType' as a second template parameter to Base, but I'm still curious why this... | At the time that the templated class Base is instantiated as a parent of the class Derived, the class Derived is not a complete type.
Since Base<Derived<DataClass> > is a parent class of Derived<DataClass>, it must be instantiated before Derived<DataClass> can be instantiated. So when the class Base<Derived<DataClass>... |
1,364,953 | 1,364,975 | global variable not printing correctly in visual studio | I am playing around with some recursion, and trying to count the number of additions in a recursive fib function (code below). The problem is, g_add never gets printed as anything but zero (0). In the debugger it is set correctly, but it wont print correctly. In fact, the code below is modified a bit, to sanity check t... | You're assuming the order in which the parameters are evaluated.
Use this instead:
int fib = rfib(n);
printf("Fib %d is: %d - additions: %d\n", n, fib, g_add);
|
1,365,206 | 1,365,280 | Should the "this" pointer and smart pointers be mixed? | How should I avoid using the "this" pointer in conjunction with smart pointers? Are there any design patterns/general suggestions on working around this?
I'm assuming combining the two is a no-no since either:
you're passing around a native pointer to a smart pointer-managed object which defeats the point of using th... | Combining the two can be done, but you always need to keep clear in your mind about the ownership issues. Generally, the rule I follow is to never convert a raw pointer to a smart pointer (with ownership), unless you are sure that you are taking ownership of the object at that point. Times when this is safe to do shoul... |
1,365,247 | 1,366,320 | How should smart pointers get down casted? | Do smart pointers handle down casting, and if not what is a safe way of working around this limitation?
An example of what I'm trying to do is having two STL vectors (for example) containing smart pointers. The first contains smart pointers to a base class while the second contains smart pointers to a derived class. ... | Smart pointers can handle downcasting, but it's not automatic. And getting const-correctness in can be a bit complex (I've used our smart pointer implementation in interview questions, there's some template trickery involved). But many users of smart pointers never instantiate their smart pointers with const-qualified ... |
1,365,291 | 1,365,304 | keep cmd open while running a file | I'm learning C++ and I'm using Visual C++ Express and while running this
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
}
the cmd window closes so fast, I can't see Hello World
is there anyway to prevent this?
| If you press Control + F5, you won't be attached with a debugger - however, it'll stay open with a "Press any key to continue" style message.
|
1,365,317 | 1,365,329 | Print to console without flooding in C++ | My apologies for an inaccurate title, but I'm not sure what this is called exactly.
How would one print to the console a single, updating line?
For example, if I wanted to print a percent completion status every cycle but not flood the console with steams of text, how would I accomplish this? (What is this called? -- f... | There is no portable way to clean the screen though there is a simple way to return to the beginning of the line using \r then overwriting what we wrote before. I am using Sleep from Windows API:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for(int i = 1; i <= 10; i++)
{
std::cout << ... |
1,365,662 | 1,365,718 | Can't link libpqxx in MinGW | Using MSYS, I compiled libpq (from compiling postgres). I then compiled libpqxx. Now, I want to create a client that will use libpqxx. libpq seemed to work fine. And, I can compile code with libpqxx. However, linking the libpq client application fails.
Here's my code:
#include <pqxx/pqxx>
#include <iostream>
usin... | The Unix linker traditionally processes libraries from left to right. So it first considers ws2_32, finds that it has not much use, then goes on to pqxx, and sees that select is undefined and doesn't get defined by any of the later libraries. IOW, try moving ws2_32 to the end of the command line.
|
1,365,711 | 2,201,866 | pthread thread state | Is there a mechanism that I can use to tell if a pthread thread is currently running, or has exited? Is there a method for pthread_join() that is able to timeout after a specific period of time if the thread has not yet exited?
| I just ended up wrapping the thread in a C++ class and keeping a state variable around that could be checked later.
|
1,365,729 | 1,365,750 | making an exe low priority | How do I run a .exe as low priority? I know I can go to task manager, and change the priority setting there manually, but is there a way that I can launch the .exe from a .bat file with a command to make the .exe run at a given priority (in this case low)? The .exe is a program that I've written in C++; can I set the p... | In a batch file, you can use the start command:
Starts a separate window to run a specified program or command.
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
... |
1,366,095 | 1,366,475 | Game engine development question | I am thinking of making a simple game engine for my course final year project. I want it to be modular and expandable so that I can add new parts if I have time. For example I would make a graphics engine that would be completely independent of the other systems, once that was finished I could add a physics engine etc.... | If you can pull this off even under a relaxed set of goals, you're set for a great project. First, you need to get a grasp of scope:
How long do you have to work on the project?
How many people are working on the project?
If you can only create one "piece of the pie" on your own, which one would you pick? Use this to ... |
1,366,148 | 1,366,170 | Terminate Excel Application using OLE | How can I mannually terminate an excel application using OLE Automation?
I would like to do this in some exception handling so that an excel process does not remain running if a function throws an error.
Currently I use the below code to open excel:
Variant excel = Variant::CreateObject("Excel.Application");
| Like this:
OleVariant excel;
excel = Variant::CreateObject("Excel.Application");
//
// Your code
//
excel.OleProcedure("Quit");
|
1,366,217 | 32,269,026 | Check if Outlook is installed on PC | Is there a way that I could programatically detect if Microsoft
Outlook (any version of it) is installed on the PC. I have to do it in unmanaged c++.
| At MSDN is an example of how to detect Outlook version (or if Outlook is installed at all). Below is a prettified version of that example:
#include <Windows.h>
#include <Msi.h>
#include "stdafx.h"
static int compareOutlookVersion(const TCHAR* exe)
{
const TCHAR outlookRegister[][MAX_PATH] = {
TEXT("{E83B4... |
1,366,232 | 1,366,741 | How many render targets do low end Pixel Shader 2.0 supporting video cards support? | MRT allows for rendering to multiple texture targets in the pixel shader, but I'm not sure how many targets that is.
I'm currently using 3 render targets but I may need as much as 5 (though probably just 4). I think the Radeon 9500s are pretty much entry level ps/vs 2.0 cards but I'm really not sure how many render tar... | Non definitive answer:
ATI R600 and above have up to 8
(Earlier cards, 9x00 and up also have MRT, but I'm not sure how many)
NVidia 6x00 and above have up to 4
(I thought G80+ was supposed to do 8, but mine says only 4)
The number for your current card is in the DX Caps member "NumSimultaneousRTs"
I's say 4 is probably... |
1,366,277 | 1,366,283 | C++: Confusing declaration semantics | After trying my hand at Perl and a little bit of C, I am trying to learn C++ and already i am bogged down by the details and pitfalls. Consider this:-
int x = 1;
{
int x = x; // garbage value of x
}
int const arr = 3;
{
int arr[arr]; // i am told this is perfectly valid and declares an array of 3 ints !!
}
Huh... | Welcome to the universe of C++!
For your question, the answer lay in a concept called 'Point-of-declaration'.
>>int x = 1;
>>{ int x = x; } // garbage value of x
From Section:-3.3.1.1 (C++ Standard Draft)
The point of declaration for a name is immediately after its complete declarator and before its initializer (if a... |
1,366,365 | 1,367,128 | Imagemagick problem when loading a png file | I've compiled the latest version of imagemagick for the mac and I get the assertion below when I load a particular png file. This is a bit of a hassle as it crashes the program in debug mode. Anyone ever seen this before? Any workarounds?
Assertion failed: (quantum_info->signature == MagickSignature),
function Destro... | From "A Basic Introduction to PNG Features" - Integrity Checks -
PNG supports three main types of integrity-checking to help avoid problems with file transfers and the like. The first and simplest is the eight-byte magic signature at the beginning of every PNG image. It will detect the most common type of file corrup... |
1,366,378 | 1,366,397 | std::string's character reference | I have the following string:
index 0 1 2 3 4 5 6 7
std::string myString with the content of "\xff\xff\xff\x00\xff\x0d\x0a\xf5"
When I'm refering to myString[3], I get the expected '\x00' value.
But when I'm referring to myString[5], I get two values "\x0d\x0a" instea... | Are you sure this is happening with std::string? std::string::operator[] returns a const char &, so how can it be returning two chars ('\x0d' and '\x0a')?
That said, "\x0d\x0a" is usually used for line endings under Windows, whereas only '\x0a' is used under Linux, so conversion of the former to the latter is relativel... |
1,366,388 | 1,366,416 | Capturing text change events in a QComboBox | I am developing a Qt application on Red Hat Linux. I want to capture Carriage Return key press events in a QComboBox.
I have connected a slot to the signal editTextChanged() which is emitted for every key press but not for the Enter Key.
Why so? Is there any other way to detect Carriage Returns?
| I am assuming you wrote a slot and connected it to QComboBox::editTextChanged() signal.
This signal is fired when the text changes and Enter does not change the text, it accepts it. If you want to capture Carriage Return, there are a number of ways you can follow.
Subclass QComboBox.
Override keyPressEvent() : first c... |
1,366,401 | 1,366,404 | How can I handle dependencies on public functions that have to be called in a certain order? | Suppose I have a class that processes some data:
class SomeClass
{
public:
void SetData(IData*);
void ProcessData(void);
}
The class would need the data to be set before ProcessData() can be called. How can I enforce this dependency? I could return an error code or throw an exception if ProcessData() is call... | Make the SomeClass constructor require IData and remove SetData. Similarly, you could also pass IData to ProcessData.
|
1,366,437 | 1,366,460 | Optimizing a floating point division and conversion operation | I have the following formula
float mean = (r+b+g)/3/255.0f;
I want to speed it up. There are the following preconditions
0<= mean <= 1 and 0 <= r,g,b <= 255 and r, g, b are unsigned chars
so if I try to use the fact that >> 8 is like dividing by 256 and I use something like
float mean = (float)(((r+b+g)/3) >> 8);
... | Pre-convert your divisions into a multiplicable constant:
a / 3 / 255
is the same as
a * (1 / (3 * 255))
so pre-compute:
const float AVERAGE_SCALE_FACTOR = 1.f / (3.f * 255.f)
then just do
float mean = (r + g + b) * AVERAGE_SCALE_FACTOR;
since multiplying is generally a lot faster than dividing.
|
1,366,470 | 1,366,513 | C++ app on SunOS has a memory leak. How to find it? | i just landed on SunOS:
$ uname -a
SunOS sunfi95 5.9 Generic_122300-13 sun4u sparc SUNW,Sun-Fire-880
and have Sun studio:
$ CC -V
CC: Sun C++ 5.8 2005/10/13
How I can find memleaks in code? (dbx is not a option in this case).
Valgrind does not work on sparc systems, only one solution that cross my mind is to use som... | On Sun OS you can use Purify, or try to port(generally you'll port the leak, too) your program to Unix/Linux and use valgrind to find the leak.
|
1,366,524 | 1,366,539 | Boost.Any vs. Boost.Variant | I'm having trouble choosing between Boost.Any and Boost.Variant.
When should I use each one?
What are the advantages and disadvantages of each?
I am basically looking to store some states from external sources.
| Have you looked at the comparison in the variant library already?
(Not sure what states from external sources are, so it's kind of hard to say what's more appropriate for you.)
|
1,366,599 | 1,368,296 | Throwing a JavaScript exception from C++ code using Google V8 | I'm programming a JavaScript application which accesses some C++ code over Google's V8.
Everything works fine, but I couldn't figure out how I can throw a JavaScript exception which can be catched in the JavaScript code from the C++ method.
For example, if I have a function in C++ like
...
using namespace std;
using na... | Edit: This answer is for older versions of V8. For current versions, see Sutarmin Anton's Answer.
return v8::ThrowException(v8::String::New("Exception message"));
You can also throw a more specific exception with the static functions in v8::Exception:
return v8::ThrowException(v8::Exception::RangeError(v8::String::Ne... |
1,366,896 | 1,366,920 | C++ templates and implicit type conversion | I have the following code:
#include <iostream>
#include "boost/shared_ptr.hpp"
using boost::shared_ptr;
class Base {
public:
virtual ~Base() {}
virtual void print() = 0;
};
template <typename T>
class Child : public Base {
public:
virtual void print() {
std::cout << "in Child" << std::endl;
}
};
class... | You don't get to the point of type conversion. It fails earlier, in template instantiation.
call_base_print doesn't require type deduction. call_print<T>(shared_ptr<Child<T> > a) does. You're passing a shared_ptr<GrandChild>. And there's simply no T you can substitute such that shared_ptr<Child<T> > is shared_ptr<Grand... |
1,367,110 | 1,385,304 | Cross-platform crash handler | I'm looking for a cross-platform crash handler. Google Breakpad looks promising, but it is sorely lacking any documentation, and requires a reasonable amount of fiddling to actually get going.
What is a better alternative?
All I need is the ability to reliably record crash dumps, stack traces, and CPU information at t... | Well, it turns out that google-breakpad is pretty nice after all. It's not totally easy to set up, but it's OK for what I need.
|
1,367,316 | 1,368,601 | #include <> and #include "" |
Possible Duplicate:
what is the difference between #include <filename> and #include “filename”
Is there a fundamental difference between the two #include syntax, apart from the way the path the compiler will search for?
I have the feeling that Intel's compiler does not give exactly the same output.
| The C language standard says that <> is to be used for "headers" and "" is to be used for "source files". Now, don't get all up in arms about the "source files" thing. When the standard says "source files", it doesn't mean what you think. The term "source files" as used in the standard encompasses what we colloquially ... |
1,367,335 | 1,367,346 | ostringstream and ends | I've been working with somebody else's code and noticed that on all uses of ostringsteam they are in the habit of explicitly appending std::ends.
This is something I've never done and have never encountered a problem.
It doesn't appear to, but should std::ends make any difference in the following code?
ostringstream me... | Appending std::ends is nonsense here since stringstream’s c_str returns a null-terminated char*. The same was not the case for the (now deprecated) strstreams where appending std::ends was necessary. I believe the author simply didn’t know of this changed behaviour.
|
1,367,429 | 1,367,494 | Sorting a std::map by value before output & destroy | I'm aware that map is not prepared to be sorted. It's heavily optimized for fast and random key access and actually doesn't support std::sort.
My current problem is that I've a full map<std::string,int> which I'm not going to use anymore. I just need to extract 10 pairs in value(int) order and destroy it.
The best thin... | Maps are stored as a tree sorted in key order. You want the 10 smallest (or largest) integer values, and their keys, right?
In that case, iterate the map and put all the key-value pairs in a vector of pairs (std::vector<std::pair<std::string, int> >). I think you can just use the two-iterator-arg constructor of std::ve... |
1,367,558 | 1,388,182 | Prevent zoom in CDHTMLDialog (BHO on IE) | I have a CDHTMLDialog running in IE that has a fixed size that I chose, and runs in a fixed window to match this size.
My problem is that the user can zoom on it (by ctrl-mousewheel) causing my html to be larger or smaller than the window which looks awkward and adds annoying scrollbars. Also, the user might use ctrl-... | Found it :)
Upon document complete I run the following:
CComVariant vZoom = 100;
m_pBrowserApp->ExecWB(OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT_DODEFAULT,&vZoom, NULL);
Which resets zoom in my DHTMLDialog to 100%.
Source: Here
|
1,367,649 | 1,368,535 | Is there a way to apply an action to N C++ class members in a loop over member names (probably via pre-processor)? | The problem:
I have a C++ class with gajillion (>100) members that behave nearly identically:
same type
in a function, each member has the same exact code done to it as other members, e.g. assignment from a map in a constructor where map key is same as member key
This identicality of behavior is repeated across many-m... | Boost.Preprocessor proposes many convenient macros to perform such operations. Bojan Resnik already provided a solution using this library, but it assumes that every member name is constructed the same way.
Since you explicitely required the possibily to declare a list of IDs, here is a solution that should better ful... |
1,368,240 | 1,368,280 | Workaround for stack limit in windows with gnu g++ | I have built and compiled a command line program with GNU g++ which "overflows" the stack for a number of reasons, mainly deep inheritance, lots of objects created, etc. So I followed this workaround on Mac OS X to solve the problem when linking:
-Wl,-stack_size,0x10000000,-stack_addr,0xc0000000
Under Linux, I just tr... | -Wl,--stack,somelargesize looks like what you're after. However, I'd strongly recommend refactoring your code to make use of the heap for large allocations instead. Address space is a finite resource and your "workaround" asks for quite a large chunk of it.
|
1,368,429 | 1,368,995 | Unrolling small loops with Visual Studio 2005 | How do you tell the compiler to unroll loops based on the number of iterations or some other attribute? Or, how do you turn on loop unrolling optimization in Visual Studio 2005?
EDIT: E.g.
//Code Snippet 1
vector<int> b;
for(int i=0;i<3;++i) b.push_back(i);
As opposed to
//Code Snippet 2
vector<int> b;
... | It's generally fairly simple: "You enable optimizations".
If you tell the compiler to optimize your code, then loop unrolling is one of the many optimizations it tries to apply.
Keep in mind though, that unrolling is not always going to produce faster code. It might cause cache misses (in both data and instruction cach... |
1,368,451 | 1,368,515 | Is Qt classified as a c++ library? If not a library, how would you classify QT? | I recently started looking into Qt (I installed Qt 4.5.2 and installed their Eclipse-CDT plugin called "qt integration v1.5.2" and I will do all my development in Linux-Eclipse-CDT-QTintegration).
Originally I thought Qt was a straight vanilla C++ library but when I installed and started running Qt example code I saw l... | Qt is a framework, not a library. This isn't a hard-and-fast distinction enforced by the programming language, rather, it describes how the code is designed and intended to be used:
A library is someone else's code that is used by your code. Using a library means that your application remains as it is, it just has an... |
1,368,512 | 1,368,564 | What is the purpose of the *.pro file? | I just started using Qt and noticed that in each example code folder there is a .pro file (and there is also a makefile created too... why?). What is the purpose of the .pro file?
| It's a multiplatform project file which qmake turns into platform-specific makefiles. The main reason for its existence is easier configuration and compilation of multiplatform projects. Compare e.g. to autotools-generated configure scripts and makefiles commonly seen in unixland.
|
1,368,534 | 1,368,577 | Why does Qt use its own make tool, qmake? | I just started using Qt and noticed that it uses its own make tool, qmake.
Why does Qt use its own make tool?
Is there something special that prevents it from using a standard make tool?
Does qmake call the GCC C++ compiler?
| Qt uses qmake to transparently support Qt's various addons, including "moc, the meta-object compiler" (which provides signals & slots), "uic, the ui compiler" (which creates header files from .ui designer files), "rcc, the resource compiler" (which compiles resources).
There's nothing to stop you using any build system... |
1,368,551 | 1,368,581 | Can you use the standard GDB debugger with Qt executables? | I just started using Qt and I wanted to debug my Qt application. Can I use the standard GDB debugger with Qt executables?
| Yes you can. You might also want to use the gdb integration in Qt Creator, which does a much better job of inspecting data at run time than gdb alone.
|
1,368,584 | 1,368,739 | What does the Q_OBJECT macro do? Why do all Qt objects need this macro? | I just started using Qt and noticed that all the example class definitions have the macro Q_OBJECT as the first line. What is the purpose of this preprocessor macro?
| From the Qt documentation:
The Meta-Object Compiler, moc, is the
program that handles Qt's C++
extensions.
The moc tool reads a C++ header file.
If it finds one or more class
declarations that contain the Q_OBJECT
macro, it produces a C++ source file
containing the meta-object code for
those classes. Amo... |
1,368,593 | 1,368,841 | Qt question: How do signals and slots work? | How do signals and slots work at a high level abstraction?
How are signals and slots implemented at a high level abstraction?
| I've actually read this Qt page about it, and it does a good job of explaining:
https://doc.qt.io/qt-5/signalsandslots.html
|
1,368,642 | 1,368,873 | Is there a shorter way to forward declare a class in a namespace? | I can forward declare a function in a namespace by doing this:
void myNamespace::doThing();
which is equivalent to:
namespace myNamespace
{
void doThing();
}
To forward declare a class in a namespace:
namespace myNamespace
{
class myClass;
}
Is there a shorter way to do this? I was thinking something along the ... | No, however with a little reformatting
namespace myNamespace { class myClass; }
isn't much worse than
class myNamespace::myClass;
|
1,369,292 | 1,369,750 | Is it possible to generate a global list of marked strings at compile time/runtime? | So, I'm working on translating my C++ app into multiple languages. What I'm currently using is something like:
#define TR(x) (lookupTranslatedString( currentLocale(), x ))
wcout << TR(L"This phrase is in English") << endl;
The translations are from a CSV file which maps the english string to the translated string.
"T... | I think you're almost there. Taking the last idea:
class TrString
{
public:
static std::set< std::string > sEnglishPhrases;
std::string phrase;
TrString(const std::string& english_phrase ):phrase(english_phrase)
{ sEnglishPhrases.insert( english_phrase ); }
friend ostream &operator<<(ostream &strea... |
1,369,530 | 1,370,100 | Registry hive question | Does anyone have a smal example of how to programmatically, in c/c++, load a users registry hive? I would loike to load a hive set some values and close the hive.
Thanks in advance for any help.
Tony
| I haven't got a specific example, but the Windows API calls you need would be:
RegOpenKeyEx() to load the registry
key
RegSetValueEx() / RegGetValue() [and sister
functions] to get/set registry values
RegCloseKey() to close the
registry.
There's some example code behind this link on codersource.net ... although I ca... |
1,369,827 | 1,375,128 | Reconnect to Process Started Via COM | First, I'd like to note that I need to use the COM/OLE2 APIs, the low level stuff, the stuff you can put in a C Windows Console program. I can't use MFC. I can't use .NET.
My question is:
Given the following code:
CLSID clsid;
HRESULT hr;
hr = CLSIDFromProgID(L"InternetExplorer.Application", &clsid);
assert(SUCCE... | If the application registered itself in the Running Object Table, you can use the GetActiveObject function to get a reference to the application object.
IUnknown *pUnknown;
hr = GetActiveObject(clsid, NULL, &pUnknown);
assert(SUCCEEDED(hr));
hr = pUnknown->QueryInterface(IID_IDispatch, (void **)&(iePtr_));
assert(SUC... |
1,369,958 | 1,369,980 | Moving C++ Method Declarations from .hh to .cc File | I'm working on a C++ project in which there are a lot of classes that have classes, methods and includes all in a single file. This is a big problem, because frequently the method implementations require #include statements, and any file that wants to use a class inherits these #includes transitively. I was just thinki... | Are you looking for something like Lazy C++?
Lzz is a tool that automates many
onerous C++ programming tasks. It can
save you a lot of time and make coding
more enjoyable. Given a sequence of
declarations Lzz will generate your
header and source files.
Example from the same place:
// A.lzz
class A
... |
1,370,042 | 32,255,804 | Why is const-correctness specific to C++? | Disclaimer: I am aware that there are two questions about the usefulness of const-correctness, however, none discussed how const-correctness is necessary in C++ as opposed to other programming languages. Also, I am not satisfied with the answers provided to these questions.
I've used a few programming languages now, an... | Well, it will have taken me 6 years to really understand, but now I can finally answer my own question.
The reason C++ has "const-correctness" and that Java, C#, etc. don't, is that C++ only supports value types, and these other languages only support or at least default to reference types.
Let's see how C#, a language... |
1,370,111 | 1,370,149 | Looking for C++ implementation of OpenGL gears example | I have often seen the spinning gears OpenGL example ( I think originally done by SGI) but I today I have only been able to find C and Ruby implementations, can anyone point me to a c++ implementation?
| What, in particular, would you be looking for in a C++ implementation that the C one doesn't provide? OpenGL is a C API, and thus a C demonstration is practical. A C++ implementation would call all the same functions in the same order and to the same effect, it would likely just wrap the implementation in an object. Th... |
1,370,323 | 1,370,341 | Printing an array in C++? | Is there a way of printing arrays in C++?
I'm trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?
| Just iterate over the elements. Like this:
for (int i = numElements - 1; i >= 0; i--)
cout << array[i];
Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
|
1,370,375 | 1,371,761 | How to get excel version from c++ add-in | I have a c++ unmanaged project whose output is an .xll file which is an add-in loaded by excel at startup, this add-in can work with both versions, excel 2003 and excel 2007.
Now, what I need to do is to obtain the version of the excel instance that the user is actually using for working with my add-in.
Does anyone can... | You can call Excel4(xlfGetWorkspace, &version, 1, &arg), where arg is a numeric XLOPER set to 2 and version is a string XLOPER which can then be coerced to an integer.
The result for Excel 2007 would be 12.
You can do this in xlAutoOpen.
|
1,370,621 | 1,370,989 | How do I get mnemonics in TrackPopupMenu? | I have a win32/MFC application with a context menu that I build programatically:
CPoint pt;
GetMenuPopupPos(&pt);
CAtlString csItem = _T("&Example");
CMenu menu;
menu.CreatePoupMenu();
menu.AppendMenu(MF_STRING, IDM_EXAMPLE_COMMAND, csItem);
menu.TrackPopupMenuEx(TPM_LEFTALIGN|TPM_LEFTBUTTON, pt.x, pt.y, this, NULL);
... | By default, Windows doesn't show underlines when a context menu is invoked using the mouse -- only when it is invoked using the keyboard. You can't override this behaviour short of owner-drawing the menu.
Your shortcuts will show if the user has selected the "underline menu shortcut keys" option, or if the user invoke... |
1,370,683 | 1,370,721 | Opengl Selective glClipPlane | I have a scene drawn in openGL (openGl 1.1 win32).
I use glClipPlane to hide foreground objects to allow the user to see/edit distance parts. The selection is done natively without using openGL.
But the glClipPlane applies to all openGL elements - coordinate icons, gridlines etc and even elements drawn in gluOrtho2D on... | Isn't surrounding only the objects you want to hide with glEnable(GL_CLIP_PLANE); and glDisable(GL_CLIP_PLANE); enough?
|
1,370,749 | 1,370,952 | Whats the difference between "abc" and {"abc"} in C? | In C specifically (i suppose this also applies to C++), what is the difference between
char str[4] = "abc";
char *cstr = {"abc"};
Problems arise when i try and pass my "abc" into a function that accepts char**
void f(char** s)
{
fprintf(stderr, "%s", *s);
}
Doing the following yields a compiler error. If cast to ch... | This is an example of how pointers and arrays are not equivalent in C. In particular: the rule that arrays decay to pointers is not applied recursively
This means that an array can be used as a pointer, but a pointer-to-array cannot be used as a pointer-to-pointer. This is what you are experiencing here. This is why th... |
1,370,870 | 1,370,892 | Parse URLs using C-Strings in C++ | I'm learning C++ for one of my CS classes, and for our first project I need to parse some URLs using c-strings (i.e. I can't use the C++ String class).
The only way I can think of approaching this is just iterating through (since it's a char[]) and using some switch statements. From someone who is more experienced in ... | Weird that you're not allowed to use C++ language features i.e. C++ strings!
There are some C string functions available in the standard C library.
e.g.
strdup - duplicate a string
strtok - breaking a string into tokens. Beware - this modifies the original string.
strcpy - copying string
strstr - find string in string... |
1,370,976 | 1,370,985 | C++ Style: Prefixing virtual keyword to overridden methods | I've been having a discussion with my coworkers as to whether to prefix overridden methods with the virtual keyword, or only at the originating base class.
I tend to prefix all virtual methods (that is, methods involving a vtable lookup) with the virtual keyword. My rationale is threefold:
Given that C++ lacks an over... | I completely agree with your rationale. It's a good reminder that the method will have dynamic dispatch semantics when called. The "that method isn't virtual" argument that you co-worker is using is completely bogus. He's mixed up the concepts of virtual and pure-virtual.
|
1,371,480 | 1,371,521 | Effect of memory usage in the complexity of an algorithm | I am reading Nicolai Josuttis book on C++STL algorithms. For many algorithms such as stable_sort(), he mentions that the complexity of the algorithm n * log(n) if enough memory is available, otherwise it is n * log(n) * log(n). My question is how does the memory usage affects the complexity ? And how does STL detect su... | Looking at gcc's STL, you'll find inplace_merge in stl_algo.h. This is a traditional merge implementation of merge sort, with O(N), using a buffer the same size as the input. This buffer is is allocated through _Temporary_buffer, from stl_tempbuf.h. This invokes get_temporary_buffer, which ultimately invokes new. Shoul... |
1,371,494 | 1,535,405 | .NET symbols disappearing from assembly | I have a project that is built with native C++, as well as C++/CLI. I have the following components:
Assembly A (C++/CLI)
| uses
Assembly B (C++/CLI)
| uses
Static Lib C (Native C++)
I did a major re-write of Static Lib C, and it compiles, and other native projects that use it compile fine as well. None of Assemb... | What happened was that the header files for the symbols in question were never being included in a cpp file anywhere. The only explanation I have for why it worked is that maybe one of the other compilation units included the headers in question indirectly, but when it changed in the rewrite, the symbols were no longer... |
1,371,564 | 1,371,630 | set an attribute in XML node usig MSXML. I am struck | I try to set an attribute in a XML node using MSXML. IXMLDOMElement alone has the member function setAttribute. So I got the document element.
pXMLDocumentElement -> get_documentElement (& pElement );
pElement -> selectSingleNode ( nodePathString ,& pNode );
.
.
.
pElement -> setAttribute ( bstr , var );
I selected th... | I think you have to use the setAttributeNode API on your pNode pointer.
While you are at it read this tutorial on using MSXML. And after you have the basics covered this blog.
|
1,371,608 | 1,371,629 | C++ pointer to class | Can anyone tell me what the difference is between:
Display *disp = new Display();
and
Display *disp;
disp = new Display();
and
Display* disp = new Display();
and
Display* disp(new Display());
| The first case:
Display *disp = new Display();
Does three things:
It creates a new variable disp, with the type Display*, that is, a pointer to an object of type Display, and then
It allocates a new Display object on the heap, and
It sets the disp variable to point to the new Display object.
In the second case:
Disp... |
1,371,710 | 1,371,733 | Accessing variables from a struct | How can we access variables of a structure? I have a struct:
typedef struct {
unsigned short a;
unsigned shout b;
} Display;
and in my other class I have a method:
int NewMethod(Display **display)
{
Display *disp=new Display();
*display = disp;
disp->a=11;
}
What does **display mean? To access variable... | As Taylor said, the double asterisk is "pointer to pointer", you can have as many levels of pointers as you need.
As I'm sure you know, the arrow operator (a->b) is a shortcut for the asterisk that dereferences a pointer, and the dot that accesses a field, i.e.
a->b = (*a).b;
The parentheses are necessary since the do... |
1,371,786 | 1,371,796 | C++ string in classes | I know this is quite a ridiculous question but this is quite confusing and irritating, as something that should work simply is not. I'm using Code Blocks with the GCC compiler and I am trying to simply create a string variable in my class
#ifndef ALIEN_LANGUAGE
#define ALIEN_LANGUAGE
#include <string>
class Language
... | using namespace std;
That's what's going on.
You don't have std:: prefixing the string in your class. Everything in the standard library is in the namespace std.
It is generally regarded as bad practice to use using namespace std;, by the way. For more information on why and what to do instead, check out this question:... |
1,372,150 | 1,372,219 | Linux IDE with proper support for STL debugging | I am looking for a Linux IDE with support for STL debugging.
the problem is that with Eclipse CDT, if I inspect the vector after the push_back:
int main() {
vector<string> v;
v.push_back("blah");
return 0;
}
I get something hostile like
{<std::_Vector_base<std::basic_string<char, std::char_traits<char>, std::alloca... | QtCreator has debugger dumpers for the Qt containers, some of the STL containers and a bunch of the Qt classes. It's also more responsive than Eclipse.
See Qt Creator debugger dumpers.
|
1,372,186 | 1,372,194 | Functions accepting C/C++ array types | It seems like g++ ignores difference in array sizes when passing arrays as arguments. I.e., the following compiles with no warnings even with -Wall.
void getarray(int a[500])
{
a[0] = 1;
}
int main()
{
int aaa[100];
getarray(aaa);
}
Now, I understand the underlying model of passing a pointer and obviously... | Arrays are passed as a pointer to their first argument. If the size is important, you must declare the function as void getarray(int (&a)[500]);
The C idiom is to pass the size of the array like this: void getarray(int a[], int size);
The C++ idiom is to use std::vector (or std::tr1::array more recently).
|
1,372,288 | 1,372,306 | Vector Iterators Casting | Hey, In C++, I have a vector of type:
vector<BaseClass*> myVector;
In which, I insert (push_back) pointers of derived classes into it.
Now, I want to pop back its elements so I do this:
vector<ADlgcDev*>::iterator iter;
for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
// but before I pop it, I need ... | while (!myVector.empty())
{
((DerivedClass*)(myVector.back()))->Shutdown();
myVector.pop_back();
}
Notes:
You should probably use dynamic_cast instead of the hard cast. (If it's sure that there are only DerivedClass objects in the vector, why isn't it std::vector<DerivedClass>?)
You should probably not have to ... |
1,372,531 | 1,372,721 | Algorithm to filter a set of all phrases containing in other phrase | Given a set of phrases, i would like to filter the set of all phrases that contain any of the other phrases. Contained here means that if a phrase contains all the words of another phrase it should be filtered out. Order of the words within the phrase does not matter.
What i have so far is this:
Sort the set by the nu... | This is the problem of finding minimal values of a set of sets. The naive algorithm and problem definition looks like this:
set(s for s in sets if not any(other < s for other in sets))
There are sub-quadratic algorithms to do this (such as this), but given that N is 10000 the efficiency of the implementation probably ... |
1,372,554 | 1,372,596 | LibCurl Unicode data | I'm writing an application, and I'm currently using libcurl. The libcurl callback function works fine when I implement it for the Ansi charset, but I fail to get it working when working with Unicode characters.
int CURLConnectorAnsi::BufferWriter(char* data, size_t size, size_t nmemb, std::string* buffer)
{
int Rea... | Basically, it has nothing to do with curl and you're facing the problem of converting utf-8 to wide string. You can use something like Glib::ustring class or implement it on your own, or take a look at this code.
|
1,372,589 | 1,372,900 | How can I build imagemagick without any asserts | Right now I'm using the following:
export CFLAGS="-O2-isysroot/Developer/SDKs/MacOSX10.5.sdk -arch i386 -I/sw/include/"
export LDFLAGS="-Wl,-syslibroot,/Developer/SDKs/MacOSX10.5.sdk,-L/sw/lib/"
sudo ./configure --prefix=/sw --with-quantum-depth=16 --disable-dependency-tracking --with-x=no --without-perl --enable-stat... | When running configure do this:
./configure DEFS=-DNDEBUG
The idea is to have NDEBUG defined.
|
1,372,916 | 1,372,950 | system("c:\\sample\\startAll.bat") cannot run because of working directory? | I have an application and executables. I want my application to run my executables.
The executable files are in a folder, lets say in "c:\sample".
In this directory there is a batch file that calls my exe's. like:
start a1.exe
start a2.exe
start a3.exe
let's name it as startAll.bat
and suppose every exe has a data lik... | Call chdir("C:\\sample") before calling system(...)
Or put a cd command in your batch file
EDIT
Since you're not on C: the first lines of the batch script should be
C:
cd \sample
EDIT2
Using the suggestions made by Johannes and MattH a much better version of the BAT file would start with something like this
setlocal
s... |
1,373,062 | 1,373,171 | What are the known C/C++ optimizations for GCC | I am have a lot of code that I need to optimize and make it run faster. I used opreport to tell me where the code spends a lot of time. I use the following command to get the statistics
opreport -g -l -d
Suggestions to get better statistics are appreciated using different flags, perhaps find it per line number instead... | Beware of the reports from profiling tools, they can be misleading. For instance, consider an application that does a large amount of string comparisons and not much else. A report is going to tell you that you spend >90% of your time in string comparison functions. So naturally, you decide to implement an optimized v... |
1,373,369 | 1,373,422 | Which is faster/preferred: memset or for loop to zero out an array of doubles? | double d[10];
int length = 10;
memset(d, length * sizeof(double), 0);
//or
for (int i = length; i--;)
d[i] = 0.0;
| Note that for memset you have to pass the number of bytes, not the number of elements because this is an old C function:
memset(d, 0, sizeof(double)*length);
memset can be faster since it is written in assembler, whereas std::fill is a template function which simply does a loop internally.
But for type safety and more... |
1,373,402 | 1,373,936 | Switching callstack for C++ functions | Here's my previous question about switching C callstacks. However, C++ uses a different calling convention (thiscall) and may require some different asm code. Can someone explain the differences and point to or supply some code snippets that switch C++ callstacks (preferably in GCC inline asm)?
Thanks,
James
| The code given in the previous question should work fine.
The thiscall calling convention differs only in who is responsible for popping the arguments off the stack. Under the thiscall calling convention, the callee pops the arguments (and additionally, the this pointer is passed in ecx); under the C calling convention... |
1,373,456 | 1,378,586 | How to reduce memory consumption in MingW based GUI Application? | I just noticed the memory usage of a simple win32 C based GUI application with single main window taking around 3 MB memory ( via Task Manager )
I used Dev-c++ and Mingw as compiler , and generated windows application via project wizard.
why that so ? is there any way to reduce it ?
| Found one API which can control the application memory set ,
This code can show a better result in Task manager.
SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1);
|
1,373,540 | 1,373,727 | Differences in Microsofts C++ STL for Windows CE? | anyone know of a complete list of the differences in Microsofts implementation of STL for Windows CE, compared to the full STL for desktop? I am using WinCE 6.0, with VS 2005.
I am a bit suprised that they seem to have removed so many things; for GCC it is almost the same. Thanks!
| according to Standard C++ Library Reference for Devices, the (only) differences are:
New Functionality
Stream support has been added to this version of the Standard C++ Library.
Unsupported Functionality
The Standard C++ Library for devices does not include locale support.
uncaught_exception is only supported on Windo... |
1,373,686 | 1,373,744 | Unable to catch c++ exception using catch (...) | I have a third-party library that is sometimes throwing an exception. So I decided to wrap my code in a try/catch(...) so that I could log information about the exception occurring (no specific details, just that it happened.)
But for some reason, the code still crashes. On client computers, it crashes hard and the... | AFAIK access violation don't throw exception... at least not standard ones!
Maybe catching windows-specific "native" exception would help : https://web.archive.org/web/20081022160935/http://www.gamedev.net/reference/articles/article2488.asp
|
1,373,889 | 1,373,909 | c++ how to create a directory from a path | what is a convenient way to create a directory when a path like this is given: "\server\foo\bar\"
note that the intermediate directories may not exist.
CreateDirectory and mkdir only seem to create the last part of a directory and give an error otherwise.
the platform is windows, MSVC compiler.
thanks!
| SHCreateDirectoryEx() can do that. It's available on XP SP2 and newer versions of Windows.
|
1,373,896 | 1,374,266 | boost make_shared takes in a const reference. Any way to get around this? | I am using boost shared pointers in my program, and I have a class that takes as a parameters a reference to another object. The problem I am running into is the make_shared function requires all parameters to be a const reference, and I get compile errors if my class's constructor doesn't allow const reference parame... | http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/make_shared.html says: "If you need to pass a non-const reference to a constructor of T, you may do so by wrapping the parameter in a call to boost::ref." Other text on that page seems to support Rüdiger Hanke's answer.
|
1,373,902 | 1,430,169 | Benefit cost analysis libraries | I was wondering if there are any opensource libraries that are geared towards transportation ben/cost analysis.
I currently use microBENCOST and would like to build my own solution. I'm most comfortable with C/c++ and Python.
cheers
| My girlfriend works for a transportation planning firm, and they use a variety of models developed in SPSS, with a lot of data munging in Excel and visualization in ArcGIS. As far as turnkey solutions go, though, I think you're going to be more or less on your own.
Assuming you want to move on to something a bit newer/... |
1,373,940 | 1,374,006 | Expected primary-expression before ',' token in strsafe.h | I'm trying to rebuild someone's old C++ project using Dev-C++ (version 4.9.9.2) and the standard compiler that it comes with (I think g++ using MinGW) under Windows XP Pro SP3 32-bit. In one of the files strsafe.h is included and when I try to compile, I get this error:
expected primary-expression before ',' token
The... | I wonder what NULL is defined as? Maybe it's not 0, it could be anything (though it would be really odd if someone defined NULL as something other than 0).
Try the following and see if it works.
#undef NULL
#define NULL 0
|
1,374,081 | 1,374,125 | How can I find the calling routine for a symbol in case of a linker error "undefined reference"? | I have a problem linking an application for an embedded target. I'm developing on a windows box using Min-GW for an ARM9 target that runs under Linux.
Actually I'm switching from static linking to dynamic linking with .so-libraries to save memory space.
I get the error message
libT3Printer.so: undefined reference to ... | The reference is probably being hidden by a macro. If you run the compiler with the -E option to generate predecessor output you might have a better chance of tracking it down.
|
1,374,265 | 1,374,274 | how can I use auto_ptr as member variable that handles another member variable | I have a class like this:
class A
{
private:
B* ptr;
}
But B ptr is shared among different A objects.
How can I use auto_ptr so that when A gets destructed B stays on so that other A objects that point to the same ptr can continue without issues.
Does this look ok:
class A
{
public:
auto_ptr< B > m_Ptr;
priva... | What you're looking for is shared_ptr. It handles exactly this type of scenario.
http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm
This is a part of the BOOST library though and not STL so it may not be available on your particular platform. However if you google around a bit you can find a lot o... |
1,374,302 | 4,916,887 | C++ Boost Code example of throwing an exception between threads | Can someone please show a simple, but complete example of how one could use Boost exception library to transfer exceptions between thread by modifying the code below?
What I'm implementing is a simple multi-threaded Delegate pattern.
class DelegeeThread
{
public:
void operator()()
{
while(true)
{
/... | I assumed you want the delegate to be executed asynchronously on a separate thread. Here is the example using boost threads and exceptions:
#include <boost/exception/all.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
class DelegeeThread
{
public:
void operator()( boost::exception_pt... |
1,374,325 | 1,374,366 | Is there any difference between type casting & type conversion? | Is there any difference between type casting & type conversion in c++.
| Generally, casting refers to an explicit conversion, whether it's done by C-style cast (T(v) or (T)v) or C++-style cast (static_cast, const_cast, dynamic_cast, or reinterpret_cast). Conversion is generally a more generic term used for any time a variable is converted to another:
std::string s = "foo"; // Conversion fro... |
1,374,372 | 1,374,444 | How to quickly find maximal element of a sum of vectors? | I have a following code in a most inner loop of my program
struct V {
float val [200]; // 0 <= val[i] <= 1
};
V a[600];
V b[250];
V c[250];
V d[350];
V e[350];
// ... init values in a,b,c,d,e ...
int findmax(int ai, int bi, int ci, int di, int ei) {
float best_val = 0.0;
int best_ii = -1;
for (int ii = 0; i... | Well, I see no obvious room for algorithmic optimizations. Theoreticaly one could only calculate the sum of the five vectors until it is obvious that the maximum cannot be reached, but this would add way to much overhead for only summing five numbers. You could try using multiple threads and assign ranges to the thread... |
1,374,468 | 1,374,485 | stringstream, string, and char* conversion confusion | My question can be boiled down to, where does the string returned from stringstream.str().c_str() live in memory, and why can't it be assigned to a const char*?
This code example will explain it better than I can
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstre... | stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.
You could copy that temporary ... |
1,374,695 | 1,374,713 | simple C++ hash_set example | I am new to C++ and STL. I am stuck with the following simple example of a hash set storing custom data structures:
#include <iostream>
#include <ext/hash_set>
using namespace std;
using namespace __gnu_cxx;
struct trip {
int trip_id;
int delta_n;
int delta_secs;
trip(int trip_id, int delta_n, int de... | So close! The last error in your output reveals your hash_trip routine should be declared const:
size_t operator()(const trip t) const // note the ending 'const'
{
//...
}
You'll probably need to do the same thing for eq_trip. Also, I would recommend passing the arguments to these functions by constant reference t... |
1,374,840 | 1,374,855 | Should boost::ptr_vector be used in place std::vector all of the time? | Just a conceptual question that I've been running into. In my current project it feels like I am over-using the boost smart_ptr and ptr_container libraries. I was creating boost::ptr_vectors
in many different objects and calling the transfer() method to move certain pointers from one boost::ptr_vector to another.
It ... | You should only use owning smart pointers and pointer containers where there's clear transfer of ownership. It doesn't matter if the object is temporary or not - all that matters is whether it has ownership or not (and, therefore, whether the previous owner relinquishes ownership).
If you create a temporary vector of p... |
1,375,201 | 1,375,324 | Lazy C++ - Chicken and Egg Problem | Based on feedback I got from this question, I'm interested in using Lazy C++ on my OSX laptop. The Lazy C++ webpage has binaries for Linux and Windows available, but nothing for OSX. There's also a link to download for the Lazy C++ source, but it requires a lzz binary as part of the build process. This creates a situat... | Given that Lazy C++ appears to be a sort of a preprocessor - generating source files as output - you could probably compile it to completion on a supported platform like Windows, take all the generated files and compile it from these generated files again on OSX.
Depending on how complex the build system (Makefiles, in... |
1,375,351 | 1,375,366 | How does fprintf work in C++? | How does fprintf work?
If I write fprintf(outfile, "test %d %d 255/r", 255, 255);
What does it mean?
I know that outfile is the name my of output file.
What would the other values mean?
| "test %d %d 255/r" tells that after it will be arguments (and they are there: 255, 255) and they are expected to be of integer type. And they will be placed instead of %d.
In result you'll get string test 255 255 255 in your file.
For more infrormation read std::fprintf reference.
|
1,375,854 | 1,376,148 | If I store a member as an object, will I incur an object copy during constuction? | If the constructor for Door looks like this:
Door::Door(Doorknob doorknob) : m_doorknob(doorknob) { }
Then you would instantiate a Door like this:
Doorknob doorknob;
Door door(doorknob); // Does an object copy of doorknob occur here?
It seems like if you store Doorknob as a pointer, you can explicitly avoid the copy... | More important than minimizing the number of copy constructor calls is that your code correctly models the problem space.
Door owns the doorknob; i.e. the lifecycle of DoorKnob is the same as that of Door. Thus, Door should manage the lifecycle of Doorknob.
The second solution is not be preferred for that reason. You... |
1,375,874 | 1,375,937 | C++ privately constructed class | How can I call a function and keep my constructor private? If I make the class static, I need to declare an object name which the compiler uses to call the constructor, which it cannot if the constructor is private (also the object would be extraneous). Here is the code I am attempting to use (it is not compilable):
I... | Based on your main code I think what you're shooting for is a singleton, which would look something like:
class Referral
{
private:
Referral()
{
//...
}
public:
static Referral& instance()
{
static Referral instance_s;
return instance_s;
}
bool submit(string url, st... |
1,376,036 | 1,377,044 | Getting a list of user profiles on a computer in C++ Win32 | What is the best way to enumerate all of the user profiles on a computer?
I know how to get the currently logged in user profile, and I know how to get the "all user" profile. But I'd like to get a list of each and every profile on the computer.
| Before going the undocumented route like flokra suggests, I would try NetUserEnum() or NetQueryDisplayInformation()
If you want to go into undocumented land, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList has a (incomplete) list of accounts (It's missing special accounts like ASPNET, HelpAs... |
1,376,085 | 1,376,099 | C++: Safe to use longjmp and setjmp? | Is it safe to use longjmp and setjmp in C++ on linux/gcc with regards to the following?
Exception handling (I'm not implementing exception handling using longjmp/setjmp. I want to know what side effects longjmp/setjmp will have on standard exception handling)
*this pointer
Signals
Smart pointers (boost's shared and in... | setjmp()/longjmp() completely subvert stack unwinding and therefore exception handling as well as RAII (destructors in general).
From 18.7/4 "Other runtime support" in the standard:
If any automatic objects would be destroyed by a thrown exception transferring
control to another (destination) point in the program, t... |
1,376,159 | 1,376,170 | paste code with syntax colors and alignment | I am looking for some blog site where i will be able to directly paste c++ code examples
in my publishes and see the code with all the alignments and colors like i see it on pastie.org.
I need all those things be made automatically because i don't know HTML and can't make by myself the code changes.
| Get wordpress + WP-Syntax.
You won't be able to "copy and paste" the code directly, but you'll have to wrap it like this:
<pre lang="c++">
CODE GOES HERE
</pre>
|
1,376,264 | 1,376,298 | Initializing static array of strings (C++)? | I can't for the life of me figure out how to do this properly. I have a class that needs to store some constants (text that corresponds to values in an enum type) - I have it declared like this (publicly) in my class:
const static char* enumText[];
And I'm trying to initialize it like this:
const char* MyClass::enumT... | This code compiles:
struct X {
static const char* enumtext[];
};
const char* X::enumtext[] = { "A", "B", "C" };
Check your code and find differences. I can only think that you did not define the static attribute in the class, you forgot to include the header or you mistyped the name.
|
1,376,626 | 1,376,635 | More efficient way of dealing with my data (ints vs floats) | My brain farts a lot when it comes to hex. Some people are abidextrous and others are just plain right handed... well, kind of like that, I'm VERY base10 I guess.
Anyway... I'm trying to make some firmware more efficient. We have a function that's calculating a vehicle's speed based on some hex data it gets via the CA... | Simply don't divide by 16.0. You can still compare, sort, add or subtract speeds.
|
1,376,792 | 1,376,794 | c++ template syntax error | My C++ is a little rusty having worked in Java and C# for the last half dozen years. I've got a stupid little error that I just cannot figure out.
I've pared the code down as much as possible.
#include <list>
template<class T> class Subscriber
{
virtual void published( T t ) = 0;
};
template <class T> class PubSub... | for( typename std::list< Subscriber<T>* >::iterator i = ...
^^^^^^^^
|
1,376,947 | 1,377,518 | Newbie Problem: C/C++ with Eclipse | My setup includes:
Windows Vista, Eclipse 3.5.0, and gdb, make, gcc 3.4.4, g++ 3.4.4 enabled through Cygwin, and environmental variable is already set.
My FIRST problem is that I can run and build an application like the information in Console:
**** Build of configuration Debug for project HelloWorld ****
make all <b... | What is sure is your second problem could very well be related to your first issue:
From this thread:
Make sure gcc is installed and on the system PATH.
This other thread states the obvious:
a PATH env var change via the OS GUI won't take effect in an already running app (Eclipse), including an already open console ... |
1,377,038 | 1,756,146 | stringstream question | Here is some code that used to work with my code, but is having a problem now:
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
using namespace std;
int main()
{
stringstream out;
out << 100;
cout << out.str();
}
I get just blank output. I just changed to snow leopard with Xcode 3.... | Get this exact same issue under the same conditions Snow Leopard 64-Bit XCode 3.2 Base SDK 10.6 and the switch to Base SDK 10.5 resolves it.
Apparently it's a SDK 10.6 issue.
and the correct workaround is to remove the preprocessor macros:
_GLIBCXX_DEBUG=1
_GLIBCXX_DEBUG_PEDANTIC=1
From the preprocessor settings (or ... |
1,377,084 | 1,377,101 | Unbuffered output with cout | How can you get unbuffered output from cout, so that it instantly writes to the console without the need to flush (similar to cerr)?
I thought it could be done through rdbuf()->pubsetbuf, but this doesn't seem to work. The following code snippet below is supposed to immediately output to the console, and then wait a f... | You can set the std::ios_base::unitbuf flag to flush output after each output operation either by calling std::ios_base::setf:
std::cout.setf(std::ios::unitbuf);
or using the std::unitbuf manipulator:
std::cout << std::unitbuf;
|
1,377,161 | 1,377,168 | Indenting in Codegear RAD Studio | Is there a way to indent/tab multiple lines in one action in the Codegear RAD Studio IDE?
i.e. I would like to be able to highlight multiple lines and indent them all by one tab simultaneously.
| Seth
to indents selected code
Select the text and press Ctrl + Shift + I
to unindents selected code
Select the text and press Ctrl + Shift + U
Bye.
|
1,377,403 | 1,378,312 | Alternative function in iostream.h for getch() of conio.h? | I'm trying to hold the screen on my output using the header file <iostream.h>, but I don't know any equivalent function to the getch() & clrscr() functions of <conio.h> in <iostream.h> or any other C++ library. Are there any such functions?
| if you work on windows you can use system("pause"), this will give you "press any key to continue" message.
|
1,377,474 | 1,381,511 | Why are my C++ exceptions not being caught? | I have some C++ code that uses a very standard exception pattern:
try {
// some code that throws a std::exception
}
catch (std::exception &e) {
// handle the exception
}
The problem is that the exceptions are not being caught and I cannot figure out why.
The code compiles to a static library in OS X (via Xcode). ... | Thanks for the input from everyone. Those are good suggestions for anyone who runs into a similar problem. It's working now, but I'm not 100% sure which of various changes I made caused things to become sane again. Once again, the approach of simplifying down to something that works and building back up from there pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.