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,532,697 | 1,715,054 | Converting from HBITMAP to Jpeg or Png in C++ | Does anyone know how I can use an HBITMAP variable to write a png or jpeg file?
I first looked into doing this with GDI+ but it gives me errors telling me min/max haven't been defined (defining them just brings more problems), I then looked into libpng's C++ bindings (png++) and couldn't get the examples to compile.
th... | HBITMAP bmp;
CImage image;
image.Attach(bmp);
image.Save("filename.jpg"); // change extension to save to png
|
1,533,017 | 1,533,123 | Dropping privileges in C++ on Windows | Is it possible for a C++ application running on Windows to drop privileges at runtime?
For instance, if a user starts my application as Administrator, but there's no reason to run my application as administrator, can I in some way give up the Administrator-privileges?
In short, I would like to write code in the main()... | Yes, you can use AdjustTokenPrivileges to remove unneeded and dangerous privileges from your token. You can either disable if not immediately needed (the privilege can be enabled later) or remove a privilege from your token altogether.
You can also create a restricted token via CreateRestrictedToken and relaunch your ... |
1,533,134 | 1,894,918 | Use gSOAP for VS 2003/C++ access to SOAP Web Service with WS-Security? | We have an upcoming project to allow an old platform that's only extensible with C++ / VS 2003 to call a SOAP-based web service that uses WS-Security.
My Google research indicates that gSOAP could be the best way to go.
I'm looking for validation and/or alternative suggestions.
| I've been using gSoap with the wsse plugin for WS-Security using signatures on both the client and server side for both Windows and Linux. It took some doing, but it works well. It is extremely fast too.
It will require you to link OpenSSL with your project. I actually found a bug in the wsse plugin a few releases b... |
1,533,361 | 1,533,489 | XP Visual Style in wxWidgets? | I'd like to know whether it is possible to enable XP Visual Style in wxWidgets,
as it is not enabled by default.
All of the controls were drawn in classic Windows style.
I'm using wxMSW packed with wxPack, but without wxFormBuilder (http://wxpack.sourceforge.net/), and MSVC++ 2008 EE as the ide.
So, is it possible to e... | Assuming that wxWidgets are - on windows - simple wrappers around the corresponding windows controls, to get the new XP theming enabled you need to add a manifest to your project that lists the common control dll version 6 as a dependent assembly.
Visual Studio has a #pragma directive to allow programmers to easilly in... |
1,533,378 | 1,533,575 | JNI Freeing Memory to Avoid Memory Leak | So i have this C++ program that is called via JNI from my Java program, the code follows:
JNIEXPORT jstring JNICALL Java_com_entrust_adminservices_urs_examples_authn_LdapAuthenticator2_takeInfo(JNIEnv *env, jobject obj, jstring domain, jstring id, jstring idca, jstring password)
{
const char *nt_domain;
co... | NewStringUTF() creates a new java.lang.String -- in other words, an object on the Java heap, which will get collected when there are no more references to it.
Or are you asking about otherString? I don't know what FormatMessage does, but it looks like it's allocating memory on the C heap. If that's the case, then yes, ... |
1,533,380 | 1,533,532 | c++ opengl converting model coordinates to world coordinates for collision detection | (This is all in ortho mode, origin is in the top left corner, x is positive to the right, y is positive down the y axis)
I have a rectangle in world space, which can have a rotation m_rotation (in degrees).
I can work with the rectangle fine, it rotates, scales, everything you could want it to do.
The part that I am ge... | What you do is rotation [ special linear transformation] of a vector with angle Q on 2d.It keeps vector length and change its direction around the origin.
[linear transformation : additive L(m + n) = L(m) + L(n) where {m, n} € vector , homogeneous L(k.m) = k.L(m) where m € vector and k € scalar ] So:
You divide your ... |
1,533,687 | 1,533,715 | Write a class using a two-dimensional dynamic array | I have a homework assignment. I'm not looking for anyone to do the work for me, I'm just having trouble with one little aspect, although I'd accept advice on other bits as well.
The assignment is:
Write a class using a two-dimensional dynamic array.
The constructor passes in the dimensions of the array. The constructo... | It's been awhile since I've done C++ development, but if I remember correctly, you'd do something like th efollowing:
int rows = 5;
int cols = 10;
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[cols];
}
I might be mistaken; I see posts to the contrary online where you have to f... |
1,533,916 | 1,533,956 | How to set up a C++ function so that it can be used by p/invoke? | Hopefully this is a brainlessly easy question, but it shows my lack of expertise with C++. I'm a C# programmer, and I've done extensive work with P/Invoke in the past with other people's C++/C dlls. However, this time I've decided to write a wrapper C++ dll (unmanaged) myself, and am then calling my wrapper dll from ... | You'll want to use extern "C" as well as __declspec(export), like so:
extern "C" _declspec(dllexport) bool TestFunc()
{
return true;
}
For full details, see MSDN on Marshalling Types.
|
1,533,917 | 1,533,990 | C++ template macro shortcut | Often when working with templates, you end up with something like:
template <T>
class the_class
{
public:
// types
typedef T value_type;
typedef const value_type const_value_type;
typedef value_type& reference;
typedef const_value_type& const_reference;
typedef value_type* pointer;
typedef const_... | Sure, what you're doing would work, but it's kind of old-school. Have you tried to put that stuff into another template class that you could derive from?
template <typename T>
class template_defs
{
public:
// types
typedef T value_type;
typedef const value_type const_value_type;
typedef value_type& referenc... |
1,534,324 | 1,534,349 | What does (int **array;) create? | I want to know what is happening in memory when you declare:
int **array;
| The compiler reserves four bytes (on a 32bit system, eight bytes on 64bit) to store a pointer (that would point to another pointer, that would point to an int). No further memory allocation is done, it is left to the programmer to actually set the pointer to point to some other memory location where the int*/array/... ... |
1,534,335 | 1,534,369 | std::string equivalent for data with null characters? | I'd like to read a binary file and use something like std::string that automatically resizes the buffer and such.
I'm using Visual C++. What are my options?
| std::string should be safe to do so... you only have to be careful using .c_str() method. Use .data().
|
1,534,399 | 1,534,415 | What's the difference between std::string::c_str and std::string::data? | Why would I ever want to call std::string::data() over std::string::c_str()? Surely there is some method to the standard's madness here...
| c_str() guarantees NUL termination. data() does not.
|
1,534,437 | 1,534,566 | I'm starting my C++ learning, using CodeBlocks and windows, what compiler should I use? | I'm under the impression certain compilers only work for making windows applications.
| If you care about portability to Unix, use the mingw compilers which are based on gcc. Gcc is widely available on a lot of architectures and OS. If you only work for Windows, Visual Studio Express might be a better choice in comparison to Codeblocks.
|
1,534,450 | 1,534,729 | C++ or Python for C# programmer? | I am a corporate C# programmer. I found some time to invest into myself and stumbed upon a dilemma. Where to go from now? C#/.NET is easy to learn, develop for, etc. In future I would want to apply to Microsoft or Google, and want to invest spare time wisely, so what I will learn will flourish in future.
So: Python or ... | C# is a little closer to Java and C++ than it is to Python, so learn Python first out of the two.
However, my advice would be:
Stick with your current language and learn more techniques, such as a wider range of algorithms, functional programming, design by contract, unit testing, OOAD, etc.
learn C (focus on figuring... |
1,534,473 | 1,534,496 | In a header file for other programm to use, can I only declare the templates? | I was wondering about using or not templates, in other thread I found out that templates must be implement in the header file because of some reasons.
Thats ok, my question is if the source will be need if other programm use it?
from the logic of the other thread's answer, it seems that even other programm would need t... | If you want users of your library to be able to use your templates, their source code needs to be available to those users.
However you can sometimes design your template classes so that most of the logic happens in non-template classes which don't have the full source code in the headers.
|
1,534,555 | 1,537,322 | C++, boost asio, receive null terminated string | How can I retrieve null-terminated string from a socket using the boost::asio library?
| m_socket = boost::asio::ip::tcp::socket(io_service);
boost::asio::streambuf replyBuf;
...
...
boost::asio::read_until(m_socket, replyBuf, '\0');
And if you want to transform the streambuf to a string:
std::string retVal((std::istreambuf_iterator<char>(&replyBuf)),
std::istreambuf_iterator<char>... |
1,534,600 | 1,534,610 | Are there any numeric suffixes for specifying a double? | void Foo(float a){} //1
void Foo(double a){} //2 overloaded
Foo(1.0f); //calls function 1
Foo(1.0 /*double numeric suffix?*/); //calls function 2
If not, is a cast the only way this can be achieved? I am mainly interested in
ensuring double precision math during certain operations, etc:... | A suffix is unnecessary in C++. Any floating point value which lacks the 'f' suffix will be typed to the compiler type double by default.
Reference: http://en.wikipedia.org/wiki/C_0x
|
1,534,659 | 1,535,608 | How to dereference a pointer passed by reference in c++? | I'm doing (something like) this:
void insert(Node*& node, string val, Node* parent)
{
if (node == NULL)
instantiateNode(node, val, parent);
else
insert(node->child, val, node);
}
The thing is, that instantiateNode(..., parent) seems to modify the original *&node passed into the function when setting th... |
there should be a way to dereference a pointer reference to get a new pointer that points to the same object.
Well, how about this?
Node* n = node;
Now you've got a non-reference pointer that points to the same object as node, exactly what you asked for.
I am 95% sure the problem you are facing has nothing to do wit... |
1,534,713 | 1,535,325 | Software or tools recommended to improve fast your C++ programming skills | List anything you think is great to improve c++ knowledge... Please be concrete when giving solutions.
| 1) Daily Read c++ , stl and related tagged question on stackoverflow , Try analyze the
problems , think of solution , and understand solution given by others
2) :) Start working on C++ in you work , If you have good senior people who do a
strict code/design review and give valid comments , you will lear... |
1,534,734 | 1,534,811 | Fast (in means of developer time) way to use a lot of C++ code from Java | Background: We are designing a physics app, that will do a lot of data analysis, but our focus is integrating physical electronic equipement.
Basically I would like to be able to call root (it's a big data analysis library from CERN written in C++) library written in C++ library from Java. Basically ability to use RO... | With any choice, you're going to need to do some wrapping. While you don't want to write JNI wrappers for every class, you could write higher level C++ classes that encompass groups of methods. Then you only need to write wrappers for the higher level classes (this approach works for other methods too, not just JNI).
|
1,534,752 | 1,534,849 | How to make C++ code draw on Java components | We are designing physics app, and we would like to have it written in Java, and also we want to use root (root is writen in C++). Root has some nice graphical features -- it is able to draw very nice 3D charts, and I'm thinking whether it's possible to embedd those charts in Java app.
Is there any way to make C++ code... | Since SWT is built to be a fairly thin wrapper around native widgets, it may be easier to work with than Swing/AWT for your particular task. I realize this particular link is a bit old, but it does show how to quickly wrap a native widget.
|
1,534,826 | 1,534,842 | Learning to create animations in C++ | does anyone know where I can learn to create and manipulate animations in c++ for the purpose of game development?
| GameDev.net would probably be a good place to start, they have links to plenty of tutorials for both DirectX and OpenGL. The NeHe OpenGL tutorials are a pretty good introduction. Microsoft alos has quite a few tutorials and sample applications that come with the DirectX SDK.
|
1,534,912 | 1,534,929 | How to build in release mode with optimizations in GCC? | What are the specific options I would need to build in "release mode" with full optimizations in GCC? If there are more than one option, please list them all. Thanks.
| http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
There is no 'one size fits all' - you need to understand your application, your requirements and the optimisation flags to determine the correct subset for your binary.
Or the answer you want:
-O3
|
1,535,004 | 1,535,031 | How to divide two doubles accurately | I have two
double a, b;
I know that the following is true
-1 <= a/b <= 1
however b can be arbitrarily small. When I do this naively and just compute the value
a/b
the condition specified above does not hold in some cases and I get values like much greater than 1 in absolute value (like 13 or 14.)
How can I ensur... | What you need to enforce is abs(a)≤abs(b). If that condition holds, then -1≤a/b≤1, regardless of floating-point precision used. Your logic error is occurring before the division, since at the division point abs(a)>abs(b) which violates your a-priori requirement.
|
1,535,105 | 1,535,309 | code blocks 8.02 console program not outputting cout statements with SDL | im currently using the SDL-devel-1.2.13-mingw32 library in code blocks 8.02. with the mingw 5.1.6 installed separately on C:\ this program compiles and runs with no errors but i can't see the last system("pause"); on the screen. When i press any key, it of course skips over the system("pause"); then code blocks tells m... | Depending on the options used to compile SDL, console output may be redirected to files called stdout.txt and stderr.txt -- this is the default for most Windows builds.
See this wiki article for a solution: http://www.libsdl.org/cgi/docwiki.cgi/FAQ_Console
|
1,535,207 | 1,535,248 | Memory leak caused by a wrong usage of scoped_lock? | I have a memory leak, and I guess it's caused by a wrong usage of scoped_lock (Boost). I however don't manage to find the exact problem, and I do believe that the way the code has been written is not completely right neither.
The code is in this class there:
http://taf.codeplex.com/SourceControl/changeset/view/31767#51... | I suggest that, instead of using a "raw" pointer to std::string, you use a boost::shared_ptr<std::string>, and pass that around. When you're done, call its reset() function; it will decrement the usage count, and free the string automatically when the count is 0.
As a bonus, you can attach boost::weak_ptr objects to th... |
1,535,249 | 1,535,294 | C++ Read File Into hash_map | I'm trying to read in a list of words and save them in a C++ STL hash_map along with their position in the alphabetically sorted file. The idea is later I'll need to be able to tell if a string is a word and whether it comes before or after a different word.
ifstream f_dict ("dictionary.txt");
__gnu_cxx::hash_map <con... | You are trying to store the same const char * for each word because your never creating any new memory for the word pulled from the file. If you print out the pointer being returned from temp_str.c_str(), it will be the same for every call within your first loop. In your second loop you're printing out the same char ... |
1,535,368 | 1,535,718 | Resource for learning Lua to use with C++? | So I have heard that Lua is a good scripting language that ties into C++. Does anyone know some good resources for picking it up, for someone with lots of C++ experience?
| You may want to look at toLua++ or Luabind for C++ integration.
As far as learning lua itself goes, the Programming in Lua book or even the Lua Reference Manual shouldn't be out of your league at all; see the documentation section of the lua website.
The usual rule applies: read lots of other code when you're getting s... |
1,535,619 | 1,763,393 | Google Geolocation API library | Is there a library out there that will get you your approximate location using the google service (https://www.google.com/loc/json)?
Google Gears has support for it as described here http://code.google.com/p/gears/wiki/GeolocationAPI There is also good doco on the web service request/response schema.
Firefox and iPhone... | please take a look at Sony PlaceEngine, it will get you the location based on the WiFi signals it can access. The down side is that users have to install the PE client. The up side is that it can be accessed by web sites and/or local apps. There is an online server DB you can query for detailed information, and a lo... |
1,535,816 | 1,535,845 | C++ partial method specialization | Is there a partial specialization for template class method?
template <class A, class B>
class C
{
void foo();
}
it doesn't work to specialize it like this:
template <class A> void C<A, CObject>::foo() {};
Any help?
| If you are already have specialized class you could give different implementation of foo in specialized class:
template<typename A, typename B>
class C
{
public:
void foo() { cout << "default" << endl; };
};
template<typename A>
class C<A, CObject>
{
public:
void foo() { cout << "CObject" << endl; };
};
To spe... |
1,535,988 | 1,536,011 | Swapping Nodes on a single linked list | I am trying to make a swapNode function that can take any two nodes and swap them. I've made an algorithm that works if they're at least 2 nodes away, but I can't seem to come up with an algorithm that will work if they are closer to each other.
Here's what I wrote so far:
void swapNode(call * &head, call * &first, cal... | Say we have:
Node1 -> Node2 -> Node3 -> Node4 -> Node5
To swap two nodes, you need to swap the next values of the ones before each of them, and also the next values of the nodes you want to swap.
So to swap, say, Node2 and Node3, you effectively have to swap Node1->next with Node2->next, and Node2->next with Node3->ne... |
1,536,026 | 1,536,312 | Touch friendly GUI in Windows Mobile | I'm porting an audio processing application written in C++ from Windows to Windows Mobile (version 5+). Basically what I need to port is the GUI. The application is quite complicated and the GUI will need to be able to offer a lot of functionality. I would like to create a touch friendly user interface that also looks ... | There are two aspects to your question:
Libraries. For this I would take a look at Qt for CE/WinMo. The C++ alternative is MFC.
GUI Design. About Face and Designing Interfaces (J. Tidwell) are a couple of good books.
Also:
make sure that your UI is finger-friendly, I hate it when I have to use a stylus.
keep in mind... |
1,536,319 | 1,554,644 | Does C# have an equivalent to #pragma pack in C++? | C# provides StructLayoutAttribute.Pack, but its behaviour is "every member gets at least the specified alignment whether it wants it or not", whereas the behaviour of #pragma pack in C++ is "every member gets the alignment it wants, unless it wants more than the specified alignment, in which case it's not guaranteed to... | After experimenting with StructLayout.Pack, it appears that it does indeed do exactly the same thing as #pragma pack in C++. Believing the MSDN documentation for StructLayout.Pack (which claimed the behaviour described in my original post) was a mistake.
|
1,536,566 | 1,540,203 | ValidateUser instead of LogonUser? | We're trying to "lock down" a computer such that we have a generic login account for Windows XP that has very few permissions. Our software is then launched via a launcher that runs it as more privileged user, allowing it to access the file system.
Then, an operator will login to our software and we were hoping to aut... | If you want more control over the login process, you can replace the built-in login with your own, using a Gina dll. Writing your own will probably mean more work then just finding the right arguments for some API calls, but if you're looking for full customization, this might be the solution for you.
|
1,536,753 | 1,536,779 | Does std::vector.pop_back() change vector's capacity? | If I allocated an std::vector to a certain size and capacity using resize() and reserve() at the beginning of my program, is it possible that pop_back() may "break" the reserved capacity and cause reallocations?
| No. The only way to shrink a vector's capacity is the swap trick
template< typename T, class Allocator >
void shrink_capacity(std::vector<T,Allocator>& v)
{
std::vector<T,Allocator>(v.begin(),v.end()).swap(v);
}
and even that isn't guaranteed to work according to the standard. (Although it's hard to imagine an impl... |
1,536,830 | 1,536,881 | List processes for specific user | Would someone be able to point me to the C++ API's that I can use to display a list of processes and the user name in Windows?
My current code uses the CreateToolhelp32Snapshot Function which shows all the processes running for all users, but I do not know what API's to use to retreieve the user name so I can filter it... | I know that using GetTokenInformation with TokenUser gets you the SID, and a quick serach reveals that LookupAccountSid should get you the corresponding account. Havent't tried that last one myself though.
|
1,536,837 | 1,536,939 | Creating generic hashtables - C++ | .NET framework has got a Dictionary<TKey,TValue> class which is implemented as hash tables and provides data retrieval in constant time (O(1)). I am looking for a similar implementation in C++. I know about std::map but in this data retrieval takes logarithmic time. Is there any good hash table implementation in C++ wh... | Also, check out C++ Technical Report 1 for std::tr1::unordered_map if a strict adherence to C++ standard is required.
Actually std::hash_map is not C++ standard but widely used anyway.
|
1,537,151 | 1,538,026 | How to get rid of C4800 warning produced by boost::flyweight in VS2008 | I get a warning when compiling below code in VS2008 with MFC turned on. Boost version 1.39
include "boost/flyweight.hpp"
include "boost/flyweight/key_value.hpp"
class Foo
{
public:
Foo(const CString& item) : mfoo(item) {}
const CString& getkeyvalue() const {return mfoo;}
private:
const CString mfoo;
};... | One of the classes in flyweight probably uses the hash_value functions (or the wrapper class hash) to calculate a hash value from a ATL::CString. This is not defined in boost directly, so you'll need to provide an implementation:
std::size_t hash_value(const ATL::CString& s)
{
// ...
}
Just looking at your compil... |
1,537,164 | 1,537,196 | How to use std::string in a QLineEdit? | I have the following problem. I am trying to integrate a large code written by me with a Qt interface.
Some of my functions return std::string. I did not succeed in making QLineEdit::setText accept them (other functions returning char do not give me problems).
What should I do? Thanks!
Giuseppe
| Try this:
std::string a = "aaa";
lineEdit->setText(QString::fromStdString(a));
You will need Qt with STL support.
|
1,537,271 | 1,537,292 | why do we need both const and non-const getters in this example | I came across this example here:
#include <vector>
#include <cstddef>
template<typename Tag>
class Ref_t {
std::size_t value;
friend Tag& element(Ref_t r, std::vector<Tag>& v) {
return v[r.value];
}
friend const Tag& element(Ref_t r, const std::vector<Tag>& v)
{
return v[r.value];
}
publi... | The difference between the two functions is that an element() of a non-const vector is itself non-const, but if the entire vector is const, then each element() is also const.
i.e.
int main() {
std::vector<A> const cva = foo();
ARef_t ar;
A const& a = element(ar, cva);
}
|
1,537,402 | 1,539,020 | Retrieve revision number in VS with qmake | My current workflow:
hg update (or whatever one uses to check out a revision)
MyProject.pro → qmake → MyProject.vcproj
Open Visual Studio, edit files
Build project
During the build step, how can I update my config.h header file with information from version control system (e.g. hg id)?
MyProject.vcproj is generated b... | You can execute external commands from inside qmake. The easiest way to make the information available in your sources would be to use a define:
HGID = $$system(hg id)
DEFINES += HGID=\\\"$$HGID\\\"
I'm not sure if you can edit an external file from qmake. You could use an external tool, but on Windows you normally do... |
1,537,518 | 1,537,534 | C++ Initialization list and memory alloc | Is the following valid?
class myClass
{
private:
...
int m_nDataLength;
boost::shared_array<int> m_pData;
...
public:
myClass(): ..., m_nDataLength(10), m_pData(new int[m_nDataLength]), ...
{
}
}
Am I right in assuming that the initialization will happen exactly in the order I... | While the initialization in your example does happen in the order you want, it's not for the reason you assume: Initialization happens in the order of the data members declaration in the class definition. The reason for this is that the destructor must destroy the members in backward order not matter which constructor ... |
1,537,578 | 1,537,837 | How to unit test an email client | I'm working on a desktop email client right now, and I want to unit test my backend. However, I can't see a way to make that work. In order for my code to work, it has to connect to a working mail server. Unless I tie my unit tests to an email account, and make sure that account matches the state my tests expect, I don... | I'm going to assume by testing the back end you are referring to the bit of code that actually talks to the Email server and to test the rest of your software you have mocked this layer.
Now this may or may not be integration tests depending on your definition unit. Frankly I don't care what you decide to call it but i... |
1,537,583 | 1,621,656 | Qt linguist & google translate | I'm looking for a way to cheat and create some very rough translations of my Qt application using Qt linguist and an already-existing translation service such as google translate.
There's a public API for google translate, so I'm hoping someone has already tried this, but I can't seem to find it. Has anyone seen anythi... | I've written an open source app to do this with gettext .po files, it wouldn't be hard to modify for Qt Linguist files. Demo and php source available at http://pepipopum.dixo.net
|
1,537,618 | 1,537,642 | What are map files generated during compilation | What info map file contain generated during compilation of project and how i enable /map option in makefile.
Language : c++
compiler : vc6
| From Microsoft's documentation for the /MAP linker option:
A mapfile is a text file that contains
the following information about the
program being linked:
The module name, which is the base name of the file
The timestamp from the program file header (not from the file system)
A list of groups in the program, wit... |
1,537,823 | 1,537,860 | How can I ask Windows to print a document? | I want to (programmatically) print documents of various types, by asking Windows to do it (using the default associated application). How can I do this (in .NET or C++/Win32 API)?
For example, if I have MS Office and Acrobat Reader installed on the machine, PDF files should be printed by Acrobat Reader, and DOC files s... | Try using the ShellExecute function.
For example, in C:
ShellExecute(my_window_handle, "print", path_to_file, NULL, NULL, SW_SHOW);
|
1,537,964 | 3,312,896 | Visual C++ equivalent of GCC's __attribute__ ((__packed__)) | For some compilers, there is a packing specifier for structs, for example ::
RealView ARM compiler has "__packed"
Gnu C Compiler has "__attribute__ ((__packed__))"
Visual C++ has no equivalent, it only has the "#pragma pack(1)"
I need something that I can put into the struct definition.
Any info/hack/suggestion ? TIA... | You can define PACK like as follows for GNU GCC and MSVC:
#ifdef __GNUC__
#define PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__))
#endif
#ifdef _MSC_VER
#define PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop))
#endif
And use it like this:
PACK(struct myStruct
... |
1,538,137 | 1,538,193 | C++ static global non-POD: theory and practice | I was reading the Qt coding conventions docs and came upon the following paragraph:
Anything that has a constructor or needs to run code to be initialized cannot be used as global object in library code, since it is undefined when that constructor/code will be run (on first usage, on library load, before main() or not... | The "not at all" part simply says that the C++ standard is silent about this issue. It doesn't know about shared libraries and thus doesn't says anything about the interaction of certain C++ features with these.
In practice, I have seen global non-POD static globals used on Windows, OSX, and many versions of Linux and... |
1,538,332 | 1,539,432 | How should I name my class, functions, member variables and static variables? | Some may feel this question is subjective. But, I feel this is among the most important things to be told to a programmer.
Is this a good function name to check for null values.
1. checkNull()
2. notNull()
3. isNull()
What if I write
checkIfNull()
I do not know how many people share the same feeling as I do, I have ... | I found this article. Felt like sharing with you guys!
|
1,538,441 | 1,539,067 | How good is this representation of a context free grammar for a parser? | i have shared the header file containing class definition of a Context Free grammar for a parser. Could you comment on the design.
this code is for my lab assignment.
may be we could get some good programming tips out of this code. is the class hierarchy good or too complicated.
#ifndef CFG_H
#define CFG_H
#include <i... | Spirit's documentation should give you a nice intro for grammar implementation (with templates). Don't know your level, maybe that's too simple, but its quite interesting :
As a grammar becomes complicated, it
is a good idea to group parts into
logical modules. For instance, when
writing a language, it might be ... |
1,539,003 | 1,539,042 | Why is it a linker error to #include this file more than once? | This question isn't so much a 'how to solve' question as its a question about why doesn't this work?
In C++ I can define a bunch of variables that I want to use across multiple files in a few ways.
I can do it like this:
int superGlobal;
#include "filethatUsesSuperglobal1.h"
int main()
{
// go.
}
That way ONLY work... | Think about if from the code perspective - there is this symbol superGlobal that points at an integer.
You have a bunch of .o files to link together into a single executable. Each of the .o files has it's own superGlobal symbol. Which should the linker use?
The extern declaration says: another of the compilations unit... |
1,539,333 | 1,539,443 | Using a class in a namespace with the same name? | I have to use an API provided by a DLL with a header like this
namespace ALongNameToType {
class ALongNameToType {
static void Foo();
}
}
Is there a way to use ALongNameToType::ALongNameToType::Foo without having to type ALongNameToType::ALongNameToType each time? I tried using using namespace ALong... | I don't know what's ambiguous, but you can avoid all conflicts with other Foo functions like this:
namespace ALongNameToType {
struct ALongNameToType {
static void Foo();
};
}
typedef ALongNameToType::ALongNameToType Shortname;
int main() {
Shortname::Foo();
}
|
1,539,385 | 1,539,430 | main() in C, C++, Java, C# | Is main() (or Main()) in C, C++, Java or C#, a user-defined function or a built-in function?
| It's a user-defined function that is necessary for a program to execute. When you go to run your program in the compiled language, the main function is what is executed. For instance, in Java, if you have a function of the signature public static void main(String ... args) in a class then that class can be executed, as... |
1,539,396 | 1,539,431 | apple's property list (plist) implementation in c++ | I'm tasked with reading Apple's property list files within a c++ application. Focusing primarily on the xml-type plist files specified in OS X, which mimic a xml-type implementation.. Apple's implementation of their property list is described here:
http://developer.apple.com/mac/library/documentation/Darwin/Reference/... | PList files are not only mimicing XML, they are XML, including valid XML headers.
Any XML reader should be able to parse these files as a result. If you're looking for a logical class that abstracts the files, I'm not aware of any existing ones. Given Apple's documentation, you should be able to write one yourself wit... |
1,539,619 | 1,540,029 | Does #include affect program size? | When my cpp file uses #include to add some header, does my final program's size gets bigger? Header aren't considered as compilation units, but the content of the header file is added to the actual source file by the preprocessor, so will the size of the output file (either exe or dll) be affected by this?
Edit: I forg... | You clarified that:
[The header has no] templates/inline functions... doesn't have any implementation detail of functions.
Generally speaking, no, adding a header file won't affect program size.
You could test this. Take a program that already builds, and check the executable size. Then go into each .cpp file and in... |
1,539,861 | 1,539,889 | what is the good gvim guifont for C/C++ programming | I am trying to find an optimal font for gvim to program in C/C++.
I currently have the following in ~/.gvimrc and I don't like it:
if has("gui_gtk2")
set guifont=MiscFixed\ 11
else
set guifont=-misc-fixed-medium-r-normal--10-100-75-75-c-60-iso8859-1
endif
set columns=80 lines=50
set guioptions-=T "hide toolba... | You can use :set guifont=* to bring up a font chooser dialog. Once you've chosen a font use :echo &guifont to see what to put in your .gvimrc. (remember to \-escape spaces)
Personally, I like Inconsolata. From my .gvimrc:
set guifont=Inconsolata\ 13
|
1,539,951 | 1,539,967 | How can I create a macro for getting the library name a class is compiled into? | How can I create a macro for getting the library name a class is compiled into? Is there some way of getting this information from make?
Essentially I'd like to do something like:
# define LIBRARY_NAME (get info from make maybe?)
...
# ifdef LIBRARY_NAME
static const char* s_lib_name = STRINGIZE(LIBRARY... | g++ allows you to use -DMACRO_NAME=MACRO_VALUE to supply macro values on the command line. Presumably other compilers have similar features.
This is equivalent to having
#define MACRO_NAME MACRO_VALUE
at the top of each file being processed.
Leaving out the =MACRO_VALUE part is equivalent to a plain #define MACRO_NAM... |
1,540,182 | 1,540,244 | Using a std::map as an associative array | So, I'm using a std::map as an associative array. The map is declared as such:
std::map<int, CustomClass*> CustomContainer;
Later on, I use the CustomContainer object as an associative array, e.g.,
CustomClass* pClass = CustomContainer[ID]
Josuttis states:
If you use a key as the index, for which no element yet exis... | An uninitialized local pointer variable or field will have undefined value, just like uninitialized int (or, in general, POD-type) local variable or field would. However, this has nothing to do with question at hand.
When you use operator[] on map, and it creates a new entry, it is default-initialized. This means null ... |
1,540,515 | 1,540,525 | Why is the output of cout << 7/9*9; is zero? | Why is the output of the following code equals to 0 or serven?
cout << 7/9*9; //output 0 (zero) why?
float nine = 9;
float seven = 7;
float i = seven/nine*nine;
cout << i //output 7 Why?
Thanks for the help.
| 7/9*9 evaluates those numbers as integers, so 7/9 evaluates to 0, and 0*9 = 0.
When you made them floats, you were performing the intended calculation.
Try 7.0/9*9 to get 7, and then you'll be doing a floating point operation.
|
1,540,659 | 1,540,668 | How do dynamically allocated arrays get freed in C++? | I know that you have to do it like this:
int * p;
p = new int[10];
//use array
delete [] p;
Now my question is: Since it's not explicitly stated, how is it possible that the correct amount of memory is freed? Do the OS keep track of the allocated memory and its starting address?
| The runtime library will keep track of allocated blocks of memory. It's guaranteed to deallocate the block correctly, given the initial pointer returned by new.
While this can be implemented in the OS itself (theoretically), it normally isn't. What the OS keeps track of is the pages allocated to a process as a whole, n... |
1,540,729 | 1,581,173 | Undefined symbol _main when trying to build logstalgia on mac | I have been trying to build the logstalgia project (http://code.google.com/p/logstalgia/) on my Mac (10.5). Rather than having to link it to the system libraries correctly, I have built and added all of the dependencies to the project. I am new at this, but I do think I have done this correctly, mostly because I have h... | I got this error to go away. If I understand, essentially SDL re-names the main function, so that it can do some stuff, then run your application, then clean up. Turns out that if you are building in Xcode, you must use ObjectiveC to compile your application.
In Xcode, telling the linker to try and use SDL_main(), rat... |
1,540,831 | 1,545,235 | stringstream temporary ostream return problem | I'm creating a logger with the following sections:
// #define LOG(x) // for release mode
#define LOG(x) log(x)
log(const string& str);
log(const ostream& str);
With the idea to do:
LOG("Test");
LOG(string("Testing") + " 123");
stringstream s;
LOG(s << "Testing" << 1 << "two" << 3);
This all works as intended, but wh... | I think I see what's happening. This produces the expected output:
log(std::stringstream() << 1 << "hello");
while this does not:
log(std::stringstream() << "hello" << 1);
(it writes a hex number, followed by the "1" digit)
A few elements for the explanation:
An rvalue cannot be bound to a non-const reference
It is ... |
1,540,859 | 1,540,884 | C2664 error in an attempt to do some OpenGl in c++ | Here is an abstract of my code. I'm trying to use glutSpecialFunc to tell glut to use my KeyPress function
class Car : public WorldObject
{
public:
void KeyPress(int key, int x, int y)
{
}
Car()
{
glutSpecialFunc(&Car::KeyPress); // C2664 error
}
}
The error message I get is:
Error 1 error C2664: 'glutSpecia... | Your function is a member of a class. When you do something like Car c; c.drive(), that drive() function needs a car to work with. That is the this pointer. So glut can't call that function if it doesn't have a car to work on, it's expecting a free function.
You could make your function static, which would mean the fun... |
1,540,960 | 1,541,370 | How to write good Unit Tests? | Could anyone suggest books or materials to learn unit test?
Some people consider codes without unit tests as legacy codes. Nowadays, Test Driven Development is the approach for managing big software projects with ease. I like C++ a lot, I learnt it on my own without any formal education. I never looked into Unit Test ... | An important point (that I didn't realise in the beginning) is that Unit Testing is a testing technique that can be used by itself, without the need to apply the full Test Driven methodology.
For example, you have a legacy application that you want to improve by adding unit tests to problem areas, or you want to find b... |
1,541,031 | 1,541,067 | Is it possible for slicing to occur with Smart Pointers? | If I understand slicing correctly I don't think this could happen with pointers or smart pointers. For example, if you had:
class A
{
int something;
};
class B : public A
{
int stuff;
int morestuff;
};
int main()
{
std::shared_ptr<B> b(new B());
std::shared_ptr<A> a;
a = b;
}
My understanding is that the... | A smart pointer is still a pointer, so such an assignment won't cause slicing. Slicing happens only when dealing with values, not pointers. Note, however, templates don't know about the relationships between the items the point at, so even though B derives from A, shared_pointer<B> doesn't derived from shared_pointer<A... |
1,541,275 | 1,541,297 | C++ stringstream returning extra character? | I've been attempting to use the C++ stringstream class to do some relatively simple string manipulations, but I'm having a problem with the get() method. For some reason whenever I extract the output character by character it appends a second copy of the final letter.
#include <iostream>
#include <sstream>
#include <st... | At the end of the stream ss.eof() doesn't know yet that the end of the stream will be reached soon, but the following extraction of a character fails. Since the extraction failed because the end of the stream was reached, c is not changed. Your program doesn't recognize that ss.get(c) failed and prints that old value o... |
1,541,560 | 1,541,651 | STL Priority Queue on custom class | I'm having a lot of trouble getting my priority queue to recognize which parameter it should sort by. I've overloaded the less than operator in my custom class but it doesn't seem to use it. Here's the relevant code:
Node.h
class Node
{
public:
Node(...);
~Node();
bool operator<(Node &aNode);
...
}
Node... | less<vector<Node*>::value_type> Means that your comparator compares the pointers to each other, meaning your vector will be sorted by the layout in memory of the nodes.
You want to do something like this:
#include <functional>
struct DereferenceCompareNode : public std::binary_function<Node*, Node*, bool>
{
bool op... |
1,541,676 | 1,542,120 | fread terminating mid-read at null values. Also reading in garbage past expected data | I am reading in pieces of a binary file using a FILE object in C++. Here is the fseek and corresponding fread call:
fseek(fp, startLocation, SEEK_SET);
fread(data, m_sizeOfData, 1, fp);
m_sizeOfData ends up being an integer greater than 400 thousand. This appears that it should read all 400 thousand+ bytes from the ... | You are using the count/size parameters of fread the wrong way around. Since you are reading bytes, the second parameter should be 1 and the third parameter the count:
fread(data, 1, m_sizeOfData, fp);
You can then use the return value of fread to determine how many bytes were read. If you are getting the expected cou... |
1,541,763 | 1,541,798 | Reading in an ascii 'maze' into a 2d array | I'm writing code to read in a 7x15 block of text in a file that will represent a 'maze'.
#include <iostream>
#include <fstream>
#include <string>
#include "board.h"
int main()
{
char charBoard[7][15]; //the array we will use to scan the maze and modify it
ifstream loadMaze("maze"); //the fstream we will u... | Try an absolute path like "c:\MyMazes\maze".
Throw in a system("cd") to see where the current directory is. If you're having trouble finding the current directory, check out this SO discussion
Here's the complete code - this should display your entire maze (if possible) and the current directory.
char charBoard[7][15... |
1,541,771 | 1,541,966 | Using Maven for C/C++ projects | I'm putting Maven build around cluster of amateur, poorly written and frankly - primitive C/C++ code (meaning some C, some C++). Problem is - there's lots of it in circulation currently and cannot be easily replaced. Building it requires a lot of tribal knowledge (you have to go from cube to cube just to find out how t... | I highly recommend the maven-nar-plugin. I find it superior in many ways to the alternatives. It doesn't require listing out source files, handles multiple OSes and architectures, handles unit and integration tests, and generally follows "the maven way". It introduces a new kind of packaging - the NAR, or "native archi... |
1,541,817 | 1,541,909 | sort function C++ segmentation fault | In this code, for vector size, n >=32767, it gives segmentation fault, but upto 32766, it runs fine. What could be the error? This is full code.
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<utility>
#include<algorithm>
#include<sys/time.h>
using namespace std;
#define MAX 100000
bool com... | In C++, your compare predicate must be a strict weak ordering. In particular, compare(X,X)
must return "false" for any X. In your compare function, if both pairs are identical, you hit the test (p1.first <= p2.first) , and return true. Therefore, this compare predicate does not impose a strict weak ordering, and the... |
1,541,901 | 1,541,934 | WinAPI function to start help file | when you open help in e.g. Windows Notepad (Help->Help Topics) no child process is started (such as hh.exe), which IMO means there is a WinAPI function called to do the job.
I searched MSDN for a while but came up with nothing.
what is this function?
| Would this help? How can I open a help file (chm or so) from my GUI developed in VC++ 2008?
There are several useful solutions in that discussion.
|
1,542,001 | 1,542,474 | C code - need to clarify the effectiveness | Hi I have written a code based upon a requirement.
(field1_6)(field2_30)(field3_16)(field4_16)(field5_1)(field6_6)(field7_2)(field8_1).....
this is one bucket(8 fields) of data. we will receive 20 buckets at a time means totally 160 fields.
i need to take the values of field3,field7 & fields8 based upon predefined co... | I had a hard time reading your code but FWIW I've added some comments, HTH:
// do shorter functions, long functions are harder to follow and make errors harder to spot
// document all your variables, at the very least your function parameters
// also what the function is suppose to do and what it expects as input
int C... |
1,542,084 | 1,543,484 | What's the most commonly used XML library for C++? | I saw a few libraries through a quick Google search. What's generally the most commonly used XML implementation for C++?
I'm planning on using XML as a means for program configuration. I liked XML because I'll be making use of its tree-like structure. If you think you have a more suitable solution for this, feel free t... | I would recommend not using XML.
I know this is a matter of opinion but XML really clutters the information with a lot of tags. Also, even though it is human-readable, the clutter actually hampers readability (and I say it from experience since we have some 134 XML configuration files at the moment...). Furthermore, it... |
1,542,108 | 1,542,206 | How to hack the virtual table? | I would like to know how to change the address of Test which is in the virtual table with that of HackedVTable.
void HackedVtable()
{
cout << "Hacked V-Table" << endl;
}
class Base
{
public:
virtual Test() { cout <<"base"; }
virtual Test1() { cout << "Test 1"; }
void *prt;
Base(){}
};
clas... | This works for 32-bit MSVC builds (it's a very simplified version of some production code that's been in use for well over a year). Note that your replacement method must explicitly specify the this parameter (pointer).
// you can get the VTable location either by dereferencing the
// first pointer in the object or by ... |
1,542,200 | 1,542,272 | Is using const_cast for read-only access to a const object allowed? | In C++ I have a function that only requires read-only access to an array but is mistakenly declared as receiving a non-const pointer:
size_t countZeroes( int* array, size_t count )
{
size_t result = 0;
for( size_t i = 0; i < count; i++ ) {
if( array[i] == 0 ) {
++result;
}
}... | Yes, it is allowed (if dangerous!). It's the actual write to a const object that incurs undefined behaviour, not the cast itself (7.1.5.1/4 [dcl.type.cv]).
As the standard notes in 5.2.11/7 [expr.const.cast], depending on the type of the object an attempt to write through a pointer that is the result of casting away co... |
1,542,220 | 1,542,347 | ASCII "graphics" library? | Is there a platform-independent C/C++ library that can draw simple "graphics" in pure ASCII in a console program? For example (VERY roughly) I could call a function in the library like rectangle(3, 6); to get the following output:
******
* *
******
Ultimately, I would love to be able to plot simple graphs based on ... | From what you have said, you don't need ASCII graphics library as they purpose is to render bitmap into ASCII characters so the look of ASCII data will become 'similar' to the bitmap. For the task you have mentioned consider writing your own library, because:
Your task is not really bitmap rendering
It is not so compl... |
1,542,339 | 1,542,413 | C++ non null terminated char array outputting | I was trying to output a not null terminated char array to a file.
Actual thing is, I am receiving packets and then printing their fields.
Now as these fields are not null terminated, for example, a data segment which has size of 512 but may or may not be completely occupied.
When I write this data to a file I am using... | If you want to put exactly maxbytes bytes, use write method
stream.write(buffer, maxbytes);
If you can have less bytes in buffer, how do you know how many of them your buffer contains? If '\0' marks buffer end, you can write:
stream.write(buffer, std::find(buffer, buffer+maxbytes, '\0') - buffer);
|
1,542,361 | 1,542,458 | Why do we need an inserter function call when doing a set_union for a set? | i need to make the call to the set_union function of STL like this:
set<int> a1, a2;
set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), inserter(a1, a1.begin());
and not
set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), a1.begin());
why is that so?
| a1.begin() is simply not an output iterator. inserter(a1,a1.begin()) returns an output iterator which will invoke the set's insert function for each element. But I'm not even sure whether the first version is even correct. You iterate over the same set you insert new elements into. (!)
Since you deal with set<> objects... |
1,542,623 | 1,542,643 | Syntax error missing ; before * | I have a header file like so:
#pragma once
#include "gamestate.h"
#include "ExitListener.h"
class InitialGameState : public GameState
{
public:
InitialGameState(Ogre::Camera *cam, Ogre::SceneManager *sceneMgr, OIS::Keyboard *keyboard, OIS::Mouse *mouse, Ogre::Root *root);
~InitialGameState(void);
virtual bo... | My guess is that ExitListener.h is including InitialGameState.h header file either directly or indirectly. So there is a circular dependency between the header file and compiler is unable to find the declaration for ExitListener. If you just need to store the pointer of ExitListener in this class then there is no need ... |
1,542,675 | 1,564,841 | Access to external window handles | I am having a problem with the program I am currently working on. It is caused by the increased security in vista/Windows 7, specifically the UIPI which prevents a window with a lower integrity level 'talking' to a higher one.
In my case, i am wanting to tell the window with a high Integrity level to move into our appl... | Just thought i would follow this up for anyone who also struggled as I have finally found a way to do this.
IL = Integrity Level.
I had 2 apps, highIL.exe and lowIL.exe, the highIL wanted to find the lowIL.exe window, set it as a child window and move it into a zone created for it on the highIL.exe. This was blocked by... |
1,542,774 | 1,542,974 | C++ reference to a shared_ptr vs reference | All,
I recently posted this question on DAL design. From that it would seem that passing a reference to an object into a function, with the function then populating that object, would be a good interface for a C++ Data Access Layer, e.g.
bool DAL::loadCar(int id, Car& car) {}
I'm now wondering if using a reference... | As sbi says, "It depends on what the function does. "
However, I think the most important aspect of the above is not whether NULL is allowed or not, but whether the function stores a pointer to the object for later use. If the function just fills in some data then I would use reference for the following reasons:
the f... |
1,542,799 | 1,542,901 | Logging facilities and Qt | What logging facilities do you use whit Qt ?
Do you choose qDebug(), qWarning(), qCritical(), qFatal() methods, or maybe something like Log4cpp (Log4cplus etc.), or maybe some custom-maked code ?
| Existing C++ logging libraries are too heavy for my tastes, so I have created a custom front-end based on ideas from Logging in C++ for the Qt qInstallMsgHandlerq back-end. It's cross-platform and thread-safe. Someday I'll clean up the code and release it to the world :)
An interesting alternative for Qt is QxtLogger.
|
1,542,892 | 1,542,900 | Two ways of calling default constructor | I have the following code:
struct B
{
//B() {}
int x;
int y;
};
void print(const B &b)
{
std::cout<<"x:"<<b.x<<std::endl;
std::cout<<"y:"<<b.y<<std::endl;
std::cout<<"--------"<<std::endl;
}
int main()
{
B b1 = B(); //init1
B b2; //init2
print(b1);
print(b2);
return 0;
}
When I start program (vs2008, ... | Default constructor for POD types fills it with zeros. When you explicitly define your own constructor you are not initialize x and y and you'll get random values (in VS debug they are filled with exact values, but in release they will be random).
It is according to C++03 Standard 8.5/5:
<...>To value-initialize an ob... |
1,542,960 | 1,543,716 | A Better Boost reference? | The thing that really turns me off about Boost is their documentation. What I need is a good reference, and instead of explaining what a good reference is to me I would give example:
java.sun.com/javase/6/docs/api/
Yes I love it. It is also this:
cppreference.com/wiki/stl/vector/start
On the other hand what I find ab... | In general, I don't find the documentation is that bad. In general again, the information is "somewhere" in there. The main problem I see is a lack of uniformity, making it difficult to find that "somewhere". As you write in your question, the docs were written by different people, and a different times, and that's pro... |
1,543,098 | 1,543,121 | I need a C++ Compiler | If possible I want one that's free, popular (so support on forums will be faster) and.... just good. I don't really know much about compilers so I don't know what exactly is good.
| Please note that I have taken the below stuff from Link :http://cplus.about.com/od/glossary/a/compilers.htm
I have coped relevant things here for more detail you can visit link directly
Microsoft Visual C++ 2008 Express.
Linkfrm.
Turbo Explorer for C++.
GCC (GNU Compiler Collection)
Digital Mars C/C++ Compiler
|
1,543,156 | 1,543,482 | time table / datebook as in Sunbird for Qt? | I would like to implement a calendar in my Qt-based program as it is already implement in Mozilla Sunbird (different colors and categories are important).
Is there any "simple" possibility to realize that or do I have to create it all by myself, beginning at zero? Is there a good tutorial to create such a calendar with... | Take a look at what KOrganizer implements. You would probably have to strip some KDE-specific functionality though.
|
1,543,157 | 1,545,961 | How can I find out how much memory my c++ app is using on the Mac | Certain operations in my app are using more memory than I think they should, and I would like to log the current memory usage to help identify which they are.
Is there a system call that will return the amount of memory currently in use?
| The following C function returns the CPU time and resident memory of process pid. To get the resources of other processes, you need root permission. You may also try getrusage(), but I never get it work properly for memory usage. Getting CPU time with getrusage() always works to me.
The function is adapted from the sou... |
1,543,193 | 1,543,221 | Why Can't I store references in a `std::map` in C++? | I understand that references are not pointers, but an alias to an object. However, I still don't understand what exactly this means to me as a programmer, i.e. what are references under the hood?
I think the best way to understand this would be to understand why it is I can't store a reference in a map.
I know I need ... | They way I understand it, references are implemented as pointers under the hood. The reason why you can't store them in a map is purely semantic; you have to initialize a reference when it's created and you can't change it afterward anymore. This doesn't mesh with the way a map works.
|
1,543,305 | 1,543,429 | Swap 2D Double Arrays in c++ | I have the following method to swap two double arrays (double**) in c++. Profiling the code, the method is accounting for 7% of the runtime... I was thinking that this should be a low cost operation, any suggestions? I am new with c++, but i was hoping to just swap the references to the arrays.
62 void Solver::Swap... | 1) Make sure your function is inlined.
2) You can inplace swap, using a XOR for instance
3) Try to force the compiler to pass arguments using register instead of the stack (even though there's lot of register stress on x86, it's worth trying) - you can use the standard register keyword or play with fastcall on MS' comp... |
1,543,736 | 1,545,079 | How do I temporarily disable a macro expansion in C/C++? | For some reason I need to temporarily disable some macros in a header file and the #undef MACRONAME will make the code compile but it will undef the existing macro.
Is there a way of just disabling it?
I should mention that you do not really know the values of the macros and that I'm looking for a cross compiler solut... | In MSVC you could use push_macro pragma, GCC supports it for compatibility with Microsoft Windows compilers.
#pragma push_macro("MACRONAME")
#undef MACRONAME
// some actions
#pragma pop_macro("MACRONAME")
|
1,543,761 | 1,544,432 | pointers and references question | #ifndef DELETE
#define DELETE(var) delete var, var = NULL
#endif
using namespace std;
class Teste {
private:
Teste *_Z;
public:
Teste(){
AnyNum = 5;
_Z = NULL;
}
~Teste(){
if (_Z != NULL)
DELETE(_Z);
}
Teste *Z(){
_Z = new Teste;
... | There is a memory leak on this line:
b->Z(new Teste);
because of the definition of the function:
void Z(Teste *value){
value->AnyNum = 100;
*_Z = *value;
}
It looks like Z without arguments was supposed to be a getter and with arguments a setter. I suspect you meant to do:
void Z(Teste *value){
value->Any... |
1,543,790 | 1,543,834 | simple c++, opengl game engine for linux? | I was wondering if anyone knew of a simple opengl game engine for linux where the source is available to read.
I basically want to read the source to get a better idea of how things are put together without worrying about the code being cross platform or having fancy particle effects or anything.
| You may be interested in Irrlicht
|
1,543,830 | 1,543,915 | send the enter button input through pipe | how to send return(enter button) character through program in windows c/c++? I want to send an external program "user name" with enter button through pipe but "\n" and "\r" and EOF are not working.
consider if pPipe is the pipe stream for sending the data to the remote process stdin...
fprintf(pPipe,"username\n");
| You can use escape sequences.
|
1,544,225 | 1,544,259 | static method with polymorphism in c++ | I have a weird issue using polymorphism.
I have a base class that implements a static method. This method must be static for various reasons. The base class also has a pure virtual method run() that gets implemented by all the extended classes. I need to be able to call run() from the static class.
The problem, of cour... | Don't pass it as a void* pointer, pass it as a pointer (or reference) to the base class:
class BaseClass
{
public:
static void something(BaseClass* self) { self->foo(); }
virtual void foo() = 0;
};
|
1,544,274 | 1,544,287 | Class dependency tool | I'm looking for a (preferably open source) tool that, given a large body of C/C++ code, will generate a visual or maybe XML graph of dependencies between classes (C++) and/or files (C).
The idea would be that, if you had to convert the code to another language, you'd like to be able to get the lowest level classes comp... | Doxygen will do some pretty neat graphs.
|
1,544,351 | 1,553,534 | Handling a SAFEARRAY returned from C# server | I need to return an array of structure (classes) from a C# library to an unmanaged C++ client. This is the function in the C# library:
[ComVisible(true)]
[Serializable]
public sealed class RetrieverProxy : IRetrieverProxy
{
public IMyRecord[] RetrieveMyRecords(long[] ids)
{
IList<IMyRecord> result = new... | It turned out that I just needed "another level of indirection". That is, a pointer to pointer vs a simple pointer.
IMyRecords** pIMyRecords;
HRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&pIMyRecords);
This did the trick.
|
1,544,850 | 1,599,270 | Open source RTP mixer/translator exe or sdk | Hi I need opens source (win 32) sdk or free server with signaling protocol, which implements RTP translator or mixer. e.g receives RTP traffic from one connection and transmits it on the other. Does not have to have conferencing capabilities.
Server should implement some kind of protocol which opens, bridges, and clos... | I haven't found nothing real.
RtpProxy approaches the goal but I wasn't able to use it because it is for linux only.
I tweaked Rtp Relay test program included in Live555
|
1,544,991 | 1,545,018 | C++: How can a public static member function access private instance member variables? | I'm writing a C++ class to read input from a file into preallocated buffers called "chunks".
I want the caller to be able to call a public static Chunk class method called GetNextFilledChunk(), which
Grabs a Chunk from an inactive chunk pool
Fills the Chunk instance from the input stream using the Chunk's private memb... | This looks a little bizarre:
Chunk::
Chunk* GetNextFilledChunk()
{
Is that a typo? Should it be:
Chunk* Chunk::GetNextFilledChunk()
{
? It looks like you're accidentally defining GetNextFilledChunk to be a plain function rather than a member of Chunk.
|
1,545,080 | 1,545,085 | C++ code file extension? What is the difference between .cc and .cpp | I have seen C++ code saved as both .cc and .cpp files. Is there a difference between the two?
The Google style guide seems to suggest .cc, but provides no explanation.
I am mainly concerned with programs on Linux systems.
| At the end of the day it doesn't matter because C++ compilers can deal with the files in either format. If it's a real issue within your team, flip a coin and move on to the actual work.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.