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 |
|---|---|---|---|---|
572,979 | 572,992 | Howto create software package in Unix/Linux? | How can we create a software package, so that
after extracting our software tar ball user can do
the typical steps?
$ gunzip < mycode.tar.gz | tar xvf -
$ ./configure
$ make
$ make install
| An alternative to the hard to understand GNU/Autools is CMake.
http://www.cmake.org/cmake/help/examples.html
e.g. KDE is using it.
|
573,275 | 573,424 | Python C-API Object Allocation | I want to use the new and delete operators for creating and destroying my objects.
The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the object and delet... | The documentation for these is at http://docs.python.org/3.0/c-api/typeobj.html and
http://docs.python.org/3.0/extending/newtypes.html describes how to make your own type.
tp_alloc does the low-level memory allocation for the instance. This is equivalent to malloc(), plus initialize the refcnt to 1. Python has it's ow... |
573,294 | 573,345 | When to use reinterpret_cast? | I am little confused with the applicability of reinterpret_cast vs static_cast. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word static. This is the cast the C++ compiler uses internally for implicit casts also.
reinterpret_casts are applica... | The C++ standard guarantees the following:
static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:
int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);
reinterpret_cast only guarantees that if you cast a point... |
573,430 | 573,496 | Include header path change from Windows to Linux | I'm porting an application written in C++ from Windows to Linux. I have a problem with the header files path. Windows uses \ and Linux uses /. I am finding it cumbersome to change this in each and every source and header file. Is there some work around?
| Always use forward slashes in #include paths. It is the compiler's job to map the path to whatever slash/directory scheme the underlying OS supports.
|
573,540 | 574,987 | How to reference Resources folder in code | I'm porting a c++ Qt application from Windows to OSX and cannot wrap my head around the .app bundle concept. I hope someone can help me understand.
My executable lives here: MyProgram.app/Content/MacOS/MyProgram.exe
My resource folder lives here: MyProgram.app/Content/Resources/
In my code I use a relative path to refe... | QApplication::applicationDirPath()
http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath
|
573,649 | 575,428 | Excel automation. How to copy more than one cell? | For instance:
//omitted
vector<_bstr_t> cellData;
Excel::_WorksheetPtr pSheet = application->ActiveSheet;
Excel::RangePtr pRange = application->Cells;
_bstr_t cellValue = pRange->Item[1][1]; //single cell
cellData.push_back(cellValue);
//omitted
Without:
MFC
ATL
Question:
How to copy, multiple cells, for in... | I've never done any Excel automation using C++, but if it works similarly as VBA macros, the WorkSheet class should have a Range property that returns a range of cells in the sheet. You can specify what range you want either by giving two cells id, or a string representing the range.
Code in pseudo VBA:
Dim range As Ra... |
574,060 | 574,088 | Declare a vector of elements of struct C,and have the number of elements be i (a input of type int) | Please look at this code (and forgive the lack of knowledge). It outputs errors that I couldn't solve. I need to declare a vector of elements of struct C,but I need the number of elements be i (a input of type int).
I also tried others approaches but in all of them I received an error (cannot convert C to int,etc). How... | Let's try with an explanation :)
cin >> array[i];
That tries to extract from cin into an object of struct C. Well, so it needs an operator>> that actually does that work:
istream & operator>>(istream &is, C &c) {
is >> c.cor; // or into whatever member
return is;
}
In addition, as another one mentioned, you ... |
574,159 | 574,172 | What is a buffer overflow and how do I cause one? | I have heard about a buffer overflow and I would like to know how to cause one.
Can someone show me a small buffer overflow example?
New(And what they are used for?)
| A buffer overflow is basically when a crafted section (or buffer) of memory is written outside of its intended bounds. If an attacker can manage to make this happen from outside of a program it can cause security problems as it could potentially allow them to manipulate arbitrary memory locations, although many modern ... |
574,177 | 574,183 | Styles of buttons on win32 C++ | i know there are some styles you can put on a button in C++ win32 exa. like BS_DEFPUSHBUTTON BS_RADIOBUTTON but i do not know all of them and also how would i go about making a user drawn button
| You can find the reference of all button styles on MSDN (as usual). And an overview of the Button control in general.
To create an owner drawn button, you need to specify the BS_OWNERDRAW flag and pocess the WM_DRAWITEM notification in the button parent window.
|
574,206 | 574,222 | Making a groupbox button win32 C++ | i have a button that is a rectangle how would i put words in it i want to make so ican click the word and it starts the progrma i know ShellExecute the style is BS_GROUPBOX
| If you have more than one program you want to start, you need a button per program you want to start.
To start you external progrma, in the button parent window, you need to process the WM_COMMAND message with the BN_CLICKED notification.
To set the text of the button, you need to send WM_SETTEXT message to the button ... |
574,285 | 575,181 | Checking existence of a txt file with C++ code | First of all, i'd to establish that i do have the text file in my Folders directory. Im using visual studio and it is where my source code is compiling.
The code below should demonstate why its not working. In visual studio.
int main( const int argc, const char **argv )
{
char usrMenuOption;
const char *cFileNa... | I always check ifs.is_open() where ifs is a ifstream.
|
574,543 | 574,554 | Writing ALL program output to a txt file in C++ | I need to write all my program output to a text file. I believe it's done this way,
sOutFile << stdout;
where sOutFile is the ofstream object that creates the file like this:
sOutFile("CreateAFile.txt" ); // CreateAFile.txt is created.
When I insert the stdout into the sOutFile object, I get some code which seems to... | This is a duplicate of: this question
You can redirect stdout, stderr and stdin using std::freopen.
From the above link:
/* freopen example: redirecting stdout */
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}... |
574,801 | 574,810 | Call C++ library in C# | I have a lot of libraries written in C++. I want to call these libraries from C#, however, I have met many problems. I want to know if there is a book or guideline to tell me how to do that.
|
DllImport - http://msdn.microsoft.com/en-us/library/aa984739(VS.71).aspx
Wrapper class - http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/67cc9eea-a4fe-48bd-b8d5-f3c8051ba896
|
574,973 | 574,980 | Exporting a class from a C++ dll? | How do I expose a class from a dll ?
The application importing the dll should be able to create the objects of the class and also he should be able to call into the member functions of the class .
Is it similar to exposing C type functions using __declspec(dllexport) ?
And also when I built the dll ( which only conta... |
Is it similar to exposing C type functions using _declspec(dllexport) ?
Yes. And the __declspec can be applied to the class.
no corresponding lib file is created
IIRC this is the default, but you can override default linker options.
|
575,455 | 576,031 | Simplest way to move an array from C++ to C#, modify it, and pass it back to C++ | I have a C# class library that contains methods that need to be used with an external application. Unfortunately this external application only supports external APIs in C/C++.
Now I've managed to get a very simple COM example working between a C++ dll and a C# DLL, but I am stuck on how I can move around array data. ... | I experimented with this a while ago but have unfortunately forgotten how it all fitted together... for my purpose it turned out to be woefully slow so I cut out the C# and went back to all C++. When you say you're primarily a C# developer I hope you understand pointers because if you don't there's no way to be gentle.... |
575,695 | 575,707 | Pass more than one argument to CreateThread | Question:
How to pass specifically two arguments to CreateThread, when:
Argument one, of type SOCKET
Argument two, an interface pointer:
_COM_SMARTPTR_TYPEDEF(Range, __uuidof(Range));
RangePtr pRange; //pass pRange
Suggestions:
For interface pointer, using CoMarshalInterThreadInterfaceInStream, accordingly,
| create a structure of these two types and pass a pointer to it. This is the standard
way of passing data to threads over single pointer.
|
576,325 | 576,338 | Compiling with operator() under GCC 3.3 Problem in Boost | I have the following snippet:
#include <boost/random/lognormal_distribution.hpp>
#include <boost/random/lagged_fibonacci.hpp>
int main() {
const double mean = 0.0;
const double sigma = 1.0;
boost::lognormal_distribution<double> lognorm_dist(mean, sigma);
boost::lagged_fibonacci44497 engine;
// the follo... | Why not just lognorm_dist( engine );? Providing "function-like" syntax is the whole point of operator(). That said, lognorm_dist.template operator() <boost::lagged_fibonacci44497>((engine)) should solve your compilation issues if I am not mistaken.
|
576,396 | 576,403 | Why does strlen() appear to return <void> in the VC++ debugger? | I have a string in C++ of type const char* passed as argument to strlen, but it returns void.
it goes like
strlen(astruct.string);
Thanks..
EDIT: Did some checking,
strlen("test");
still gives void.. why?
EDIT: Here's the image
http://img14.imageshack.us/img14/1808/strlen.png
Sorry for being unclear previously. Form... | Referring to your screen shot: your debugger is displaying <void> for strlen(...) when in fact it should display an error.
You cannot call methods and display their results in the debugger watch. The debugger will only display existing variables and data. It cannot invoke arbitrary methods on demand since the methods... |
576,572 | 576,580 | In need to program an algorithem to be very fast, should I do it as php extension, or some otherway? | Most of my application is written in PHP ((Front and Back ends).
There is a part that works too slowly and I will need to rewrite it, probably not in PHP.
What will give me the following:
1. Most speed
2. Fastest development
3. Easily maintained.
I have in my mind to rewrite this piece of code in CPP as a PHP extensi... | The answer really depends on what kind of process it is.
If it is a long running process (at least seconds) then perhaps an external program written in C++ would be super easy. It would not have the complexities of a PHP extension and it's stability would not affect PHP/apache. You could communicate over pipes, share... |
576,610 | 2,379,294 | Which is better code for converting BSTR parameters to ANSI in C/C++? | So far I've discovered I can convert incoming BSTRs to ANSI in two (of many?) ways, and I'm curious to know whether one is "better" than the other with respect to speed / efficiency etc.
The way I've been using for a while is use the USES_CONVERSION and W2A macros, e.g.
BSTR __stdcall F(BSTR p1, BSTR p2 ) {
USES_CO... | Note in the approved answer by Nick, which whilst correct shares the same problem there is with the MSDN documentation that describes the macros.
The problem is that some of the macros such as the one listed by @Nick - COLE2A, don't actually exist.
However further down the MSDN page there is some text that clues you in... |
576,620 | 576,629 | How do display functions like sprintf convert numbers to strings? | I'm trying to extract the integer and decimal parts of a floating point value, and I seem to be running into some strange rounding problems, due probably to the imprecise way floats are stored.
I have some code like this to extract the fractional part:
double number = 2.01;
int frac = int(floor(number * 100)) % 100;
... | > However the result here instead of 1 comes out as one.
What do you mean?
2.099999...
Or, more like 2.00999...
As you've noted:
int frac = int(floor(number * 100)) % 100;
will be:
int frac = int(floor(2.00999... * 100)) % 100;
= int(floor(200.999...)) % 100;
= int(floor(200.999...)) % 100;
... |
576,677 | 576,710 | How do I skip reading a line in a file in C++? | The file contains the following data:
#10000000 AAA 22.145 21.676 21.588
10 TTT 22.145 21.676 21.588
1 ACC 22.145 21.676 21.588
I tried to skip lines starting with "#" using the following code:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
int main() {
... | Is this more like what you want?
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
fstream fin("myfile.txt");
string line;
while(getline(fin, line))
{
//the following line trims white space from the beginning of... |
576,767 | 576,782 | Name mangling of c++ classes and its member functions? | Is there no way I could avoid name mangling of C++ classes and its member functions when exposed from a c++ dll.
Can't I use a def file mechanism in this regard ?
| I think the best way to do this is to provide C wrappers around the C++ library. This was quite popular 10 or more years back when I was programming in C++ but I don't know if it is done any more.
Basically, for every class C, for every constructor ctor to be exposed to create an extern "C" CPtr cCtor(....) method that... |
577,006 | 577,037 | Makefiles on windows with g++, linking a library | I've gotten fed up with MSVC++6 and how everyone is always telling me that it's a crappy compiler and such.
So now I've decided to try to use vim plus g++ and makefiles. Here's my problem; I have the following makefile:
# This is supposed to be a comment..
CC = g++
# The line above sets the compiler in use..
# The next... | First step: locate the library you are looking for. For me, it's in :
C:\Program Files\Microsoft Visual Studio\VC98\Lib
Second step, pass that directory with -L :
LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib"
Third step, pass the name of the library with -l (lowercase L):
LINKFLAGS=-L"C:\Program Fil... |
577,243 | 577,334 | Is there any reason to use this-> | I am programming in C++ for many years, still I have doubt about one thing. In many places in other people code I see something like:
void Classx::memberfunction()
{
this->doSomething();
}
If I need to import/use that code, I simply remove the this-> part, and I have never seen anything broken or having some side-... | To guarantee you trigger compiler errors if there is a macro that might be defined with the same name as your member function and you're not certain if it has been reliably undefined.
No kidding, I'm pretty sure I've had to do exactly this for that reason!
|
577,270 | 577,338 | Creating new exception in C++ | I have a C++ class and I am trying to run it in Ubuntu:
#ifndef WRONGPARAMETEREXCEPTION_H_
#define WRONGPARAMETEREXCEPTION_H_
#include <iostream>
#include <exception>
#include <string>
using namespace std;
#pragma once
class WrongParameterException: public exception
{
public:
WrongParameterException(cha... | First, #pragma once is the wrong way to go about it, learn about header include guards. Related question on SO explains why using #pragma once is the wrong way to go about it. Wikipedia explains how to use include guards which serve the same purpose without any of the downsides.
Second, you are calling the constructor ... |
577,330 | 12,493,518 | MAP file analysis - where's my code size comes from? | I am looking for a tool to simplify analysing a linker map file for a large C++ project (VC6).
During maintenance, the binaries grow steadily and I want to figure out where it comes from. I suspect some overzealeous template expansion in a library shared between different DLL's, but jsut browsign the map file doesn't ... | This is a wonderful compiler generated map file analysis/explorer/viewer tool. Check if you can explore gcc generated map file.
amap : A tool to analyze .MAP files produced by 32-bit Visual Studio compiler and report the amount of memory being used by data and code.
This app can also read and analyze MAP files produced... |
577,421 | 577,442 | Is C++ friendship among peers healthy? | Although class friendship is one of the last resorts of C++, does this pattern make sense?
class Peer
{
public:
friend class Peer;
void GetSecret(const Peer& other)
{
const std::string& secret = other.GiveSecret();
std::cout << secret << std::endl;
}
private:
const std::string& Give... | friend is not necessary in this case. An object of a class can access the private members of any other object of the same type. It should work just fine without the friend declaration.
|
577,423 | 577,446 | Saving an array value into a double variable | Greetings everyone. Having an issue compiling my script containing the following function. Three errors occur, all on the same line where I set distance += to distances [][]:
error C2108: subscript is not of integral type
error C2108: subscript is not of integral type
error C2297: '+=' : illegal, right operand has type... | Well, the array subscripts x and y are not of an integral type like int, but of type double:
double x, y, z;
...
distance += distances[x][y];
And something like the 1.46534th element of an array doesn't make sense, so the compiler complains.
|
577,465 | 577,468 | in C++, can I derive a class from a struct | The question says it all really. Am I allowed derive a class from a struct, or should I create a class that embeds my struct and defines copy constructors and an = operator to move between the two?
| In C++ struct is (almost) synonymous to a class (except of different default access level), so yes, you can.
struct A {
// fields are public by default
};
class B: public A {
// fields are private by default
};
I'm not familiar with MFC, but it looks like an attempt to maintain both C and C++ APIs.
|
577,622 | 577,751 | How can I index a lot of txt files? (Java/C/C++) | I need to index a lot of text. The search results must give me the name of the files containing the query and all of the positions where the query matched in each file - so, I don't have to load the whole file to find the matching portion. What libraries can you recommend for doing this?
update: Lucene has been suggest... | I believe the lucene term for what you are looking for is highlighting. Here is a very recent report on Lucene highlighting. You will probably need to store word position information in order to get the snippets you are looking for. The Token API may help.
|
577,780 | 577,863 | send(), returns Winsock Error 10038 | Problem:
Call to send(), returns Winsock Error 10038 against socket handle
Illustration:
acceptedSocket = accept (server, (sockaddr *)&sin, &len);
accept(), returns 0
A new thread, is created for each connection
send(), (in thread function) returns 10038
Illustration: - in thread function
//omitted
SOCKET Remote... | Isn't the problem in the line
acceptedSocket = accept (server, (sockaddr *)&sin, &len) == INVALID_SOCKET)
You make acceptedSocket the result of the comparison, but you should store the actual socket returned from accept somehow:
acceptedSocket = accept (server, (sockaddr *)&sin, &len);
isOK= acceptedSocket!=INVALID_SO... |
577,853 | 577,980 | IDE Module for Hand Drawing? | I'm currently looking for a hand drawing (2D) library/module (that would be like Paint, Paint.Net or Photoshop - but I don't need all the power of Photoshop...) that would allow me to add a drawing module to an IDE application.
That application is in it's early design phase : for instance I'm only estimating if I will ... | I think that you will need to create a module for drawing.
I have done some drawing utilities using QGraphicsView from Qt >4.3 and it's pretty easy. I will consider it.
Good luck! :D
|
578,021 | 578,532 | Is it possible to statically link Qt::phonon on windows? | Because of the dependency on DirectShow on windows, is it possible to use a static Qt with my application?
| If you link Qt statically and want to distribute your application, you will most likely require a commercial license. The LGPL license (using Qt for free) in practice mandates that you link Qt dynamically.
|
578,217 | 578,280 | Bug in Visual Studio C++ compiler? | This code behaves weird in MS Visual Studio:
char *s = "hello";
s[0] = 'a';
printf(s);
In release build with optimization turned on it ignores s[0] = 'a' and prints "hello". Without optimization or in debug build it crashes with access violation.
Is this behavior is c++ standard compliant or no? In my opinion, compil... | The reason why this code is allowed in the first place (rather than requiring the declaration to be of type char const*) is backwards compatibility to old C code.
Most modern compilers in strict mode will issue a warning for the above code, though!
|
578,259 | 578,838 | How to pass and then invoke generic callback functions without causing circular dependency | Couldn't creatively shorten the title :)
I have been using a variation of the below solution, however I always wondered if there is a better/cleaner way to implement it. I am looking for non-boost solution. We can, though, look at the implementation of boost and C++0x, as it will soon be relevant.
//Notice the use of ... | If you're just looking for clean-up advice, I'd suggest making 'My_callback' a normal class, not a class template. There's not obvious need for it to be a template in this case. Instead, make its apply operator templated or fill in A directly if My_callback only deals with A instances:
#include <tr1/functional>
clas... |
578,293 | 579,004 | Are things like "afx_msg" decorators still used by VS/MFC? | I'm working on an MFC program that started way back in the VC6 days. Back then there was a class wizard that used a bunch of decorators and markup in comments to parse class files.
For example, it would insert afx_msg in front of message handlers that it maintained. It would mark a block of code with //{{AFX_MSG_MAP(Th... | afx_msg still exists but has always been purely informative. A decorator as you put it. It's always been #defined as an empty string.
the {{ and }} markers are no longer needed since VS2003: VS is now smart enough to put things in the right place without having to rely on these markers. You'll notice that VS2003+ no lo... |
578,304 | 578,370 | How would you shorten this so that action1 and action2 only show up once in code? | if (x() > 10)
{
if (y > 5)
action1(p1, p2, p3, p4);
else
action2(p1, p2);
}
else
{
if (z > 2)
action1(p1, p2, p3, p4);
else
action2(p1, p2);
}
I real project on mine, action1 and action2 are actually 2-3 lines of code and those functions that are invoked take 6-8... | bool condition_satisfied = (x() > 10 ? y > 5 : z > 2);
if (condition_satisfied)
action1(p1, p2, p3, p4);
else
action2(p1, p2);
Or, alternatively, what Roger Lipscombe answered.
|
578,479 | 578,699 | What are the Best Components of Boost? | I've been browsing revision 1.38.0 of the Boost libraries, in an attempt to decide if there are enough jewels there to justify negotiating my company's external software approval process. In the course of writing test programs and reading the documents, I've reached a couple conclusions
of course, not everything in Bo... | I use quite frequently (and it makes my life simpler):
smart pointers (shared_ptr, scoped_ptr, weak_ptr, interprocess unique_ptr):
scoped_ptr for basic RAII (without shared ownership and ownership transfer), at no cost.
shared_ptr for more complex operations - when shared ownership is needed. However there is some co... |
578,654 | 578,672 | Static Constant Class Members | Consider the following snippet:
struct Foo
{
static const T value = 123; //Where T is some POD-type
};
const T Foo::value; //Is this required?
In this case, does the standard require us to explicitly declare value in a translation unit? It seems I have conflicting information; boost and things like numeric_limits... | You have to provide a definition in a translation unit too, in case you use the value variable. That means, if for example you read its value.
The important thing is that the compiler is not required to give a warning or error if you violate that rule. The Standard says "no diagnostic required" for a violation.
In th... |
578,753 | 578,762 | Forcing ints to initialize to 0 msvc++ | Is there any compiler setting or other way to force an int to be initialized to 0?
|
Is there any compiler setting or other way to force an int to be initialized to 0?
Unfortunately, there is no way in the language and if the compiler offers such a setting it goes against the standard and therefore should not be used.
May I ask why you need this? Is explicit initialization not enough? Or would you li... |
578,794 | 578,822 | How boost.asio discover which port is my server app listening on? | it is a little bit strange to me that boost.asio doesn`t use basic concept when client app connecting to the server - using IP address and port. May be I am a little bit noobie in Boost - and I accept that - but anyway I do not understand.
So, I have code like this to get client connected to the server on the localhost... | You are telling it that you want to connect to localhost on the port used by the daytime service. It will look up the appropriate port number in the services file (usually C:\WINDOWS\system32\drivers\etc\services under Windows, I believe /etc/services under Unix). You could also use an explicit port number there.
|
578,950 | 580,882 | I need platform-independent version of CharToOem. Does Boost have any? | I need to convert string to support multi-language messaging in my client-server app.
Can I find it in boost?
| For platform-independent codepage conversions you can use libiconv library.
Anyway, why bother using codepages at all? Use unicode.
|
579,556 | 579,570 | cygwin compile error in sys/_types.h | I am trying to use cywin to get some linux code building on a win32 machine.
I get the following VS.net 2003 error in ym compiler:
"c:\cygwin\usr\include\sys_types.h(15): error C2144: syntax error : '__int64' should be preceded by ';'
"
and
c:\cygwin\usr\include\sys_types.h(15): error C2501: 'extension' : missing stor... | I think that the extension macro may not be defined. You may want to do a text search on your cygwin header dir to see if this is the case. If so, make sure that you header search path is defined correctly, etc.
|
579,673 | 579,696 | Where should my win32 program keep its files? | Our win32 applications (written in C++) have been around for over 10 years, and haven't been updated to follow "good practices" in terms of where they keep files. The application defaults to installing in the "C:\AppName" folder, and keeps application-generated files, configuration files, downloaded files, and saved us... |
Presumably, it's "best practices" to default to installing under "c:\Program Files\AppName"
Close, but not quite. Users can configure the name of the Program Files folder and may not even have a C: drive. Instead, install to the %ProgramFiles%\AppName environment variable folder.
Note you should assume you only hav... |
579,783 | 580,090 | How to detect IP address change programmatically in Linux? | Is there a way to detect IP address changes on the local machine in Linux programmatically using C++?
| In C, to get the current IP I use:
int s;
struct ifreq ifr = {};
s = socket(PF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));
if (ioctl(s, SIOCGIFADDR, &ifr) >= 0)
printf("%s\n",
inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
Replace "e... |
579,838 | 579,915 | accessing member variable of boost thread object | I'm using an object to start boost thread and it has some public member variables which I modify in the thread (in the () operator). How can I access the object's member variables from outside the thread?
I tried using a mutex (defined in the object's class) that is locked both in the operator() of the object and from ... | boost::thread copies the passed thread function to internal storage, so if you start your thread like this, the thread will operate on a different copy of mouse:
int main() {
Mouse mouse("abc.txt");
boost::thread thr(mouse); // thr gets a copy of mouse
...
// thread changes it's own copy of mouse
...
}
You c... |
580,053 | 580,082 | When should I use a vector of objects instead of a vector of pointers? | I have a collection of polymorphic objects, all derived from my Animal class: Cat, Dog, and MonkeyFish.
My usual mode of operation is to store these objects in a vector of Animal pointers, like so:
std::vector< Animal * > my_vector;
my_vector.push_back( new Animal_Cat() );
my_vector.push_back( new Animal_Dog() );
my_v... | You should use a vector of objects whenever possible; but in your case it isn't possible.
Containers of pointers let you avoid the slicing problem. But then you have to call delete on each element, like you are doing. That's annoying but possible. Unfortunately there are cases (when an exception is thrown) where you... |
580,229 | 580,307 | Member Variable Pointers in 64 bit environment | I've discovered while trying to use a luaBind-style class binding system that passing pointers to member variables doesn't seem to work right when compiling as a 64 bit app. Specifically:
class Foo {
int a;
int b;
};
With the above class getting &Foo::b in 32 bit will return (as expected) 0x00000004. The same ... | Try printing sizeof(&Foo::b).
IIRC, in 64-bit VS2005 a pointer to member could occupy 4 or 12 bytes (depending on virtual/multiple inheritance), but IDE always displays 8 bytes (which (IMHO) is a bug in IDE ).
|
580,263 | 580,560 | Windows API and GetClassName()? Another name? | I have some code that has a dynamic-class system in C++ that has a member called GetClassName(), a rather harmless name one would imagine. However when included in a large project with Windows headers all hell broke loose. Apparently Windows uses a #define GetClassName (GetClassNameA or GetClassNameW) which screws up e... | I would rename the method.
Of course one can say
#include <windows.h>
#undef GetClassName
but it is not clean, users of one's code should remember to write ::GetClassNameW when they call win32 function.
One can provide GetClassNameA and GetClassNameW methods in his class, but it's plain ugly.
I see two approaches :... |
580,270 | 580,303 | Avoiding dynamic_cast/RTTI | I was recently working on a piece of C++ code for a side project (the cpp-markdown library, for the curious), and ran into a coding question that I'd like some opinions on.
cpp-markdown has a base class called Token, which has a number of subclasses. Two of the main subclasses are Container (which holds collections of ... | #1 pollutes the class namespace and vtable for objects that don't need it. Ok when you have a handful of methods that will generally be implemented, but plain ugly when only needed for a single derived class.
#2 is just dynamic_cast<> in a polka-dot dress and lipstick. Doesn't make client code any simpler, and tangles ... |
580,342 | 580,597 | Setting up a mock interface in C++ | I'm currently trying to use a certain SDK that has me loading functions off a DLL that a vendor provides.. I have to pass arguments to these functions and the DLL does all the work..
Now, the DLL is supposed to be communicating with another device, while I just wait for the results. However, I don't have this device, ... | Is emulated device access a stopgap solution for until you get hardware? If so, I recommend finding some other way to be productive: work on something else, write unit tests, etc.
Is emulated device access a permanent requirement? If so, here are a few approaches you could take:
If the other vendor's SDK has a "simul... |
580,363 | 580,412 | Posix Threads in c++ | How to implement posix threads in linux c++.The smme program when saved as ".c and run using c compiler is ok. but in c++ it is giving error ..
I think i made mistake when compiling
is there any tag to be included like "-lpthread" for c++
Can someone pls send a valid code...?
Actually this is my code
int cooperbuss... | Your packetreadertask function must be a function that takes a single void * as a parameter. This is the important error message:
cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â
Your function is declared something like this:
void *packetreadertask();
where it must be:
void *pa... |
580,375 | 580,533 | How to generate a compiler warning/error when object sliced | I want to know if it is possible to let compiler issue a warning/error for code as following:
Note:
1. Yea, it is bad programming style and we should avoid such cases - but we are dealing with legacy code and hope compiler can help identify such cases for us.)
2. I prefer a compiler option (VC++) to disable or enable o... | If you can modify the base class you could do something like:
class Base
{
public:
// not implemented will cause a link error
Base(const Derived &d);
const Base &operator=(const Derived &rhs);
};
Depending on your compiler that should get you the translation unit, and maybe the function where the slicing is ha... |
580,448 | 580,513 | What Visual Studio 2008 productivity features are missing from C++ Express edition? | I'm using Visual Studio C++ 2008 Express to learn a native API for a new project. What I'm wondering is: what productivity features present in the full version that you take for granted are missing from Visual Studio Express? I'm not referring to large "paid" features like MFC support - I'm thinking of small features ... | If you plan to develop a C/C++ WIN32 GUI application then the major component that is missing is the resource editor (i.e. the GUI builder tool).
The express version will still compile resource files, but you will have to create the resource files by hand or use a third party resource editor.
|
580,622 | 580,628 | Dynamic array... copy constructor, destructor, overloaded assignment operator | I am studying for my midterm exam. There is going to be a question about setting up an array dynamically, and maybe doing a copy constructor, a destructor and overloading the assignment operator. Can you please verify if I am correct. Also I don't understand what overloading the assignment operator means. Can you he... | The copy constructor is used for creation of object based on another's instance of the same type. You don't have such. You can define it using code like this:
A(const A &other)
{
myArray = new int[other._size];
_size = other._size;
memcpy(myArray, other.myArray, sizeof(int) * _size);
}
You should change your ... |
580,652 | 580,678 | Fighting fragmentation in custom memory manager | I've written a c/c++ memory manager for heap allocations (overloaded new/delete and malloc/realloc/free, based on Doug Lea's malloc but designed to be wait free) and seem to be having some trouble with fragmentation. Are there any good resources out there that detail good strategies for avoiding fragmentation via the m... | You may want to get some inspiration from jemalloc (http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf) - this allocator is used in the new Firefox explicitly because of its anti-fragmentation capabilities.
|
580,922 | 580,935 | Identifying primitive types in templates | I am looking for a way to identify primitives types in a template class definition.
I mean, having this class :
template<class T>
class A{
void doWork(){
if(T isPrimitiveType())
doSomething();
else
doSomethingElse();
}
private:
T *t;
};
Is there is any way to "implement" isPrimitiveType().
| UPDATE: Since C++11, use the is_fundamental template from the standard library:
#include <type_traits>
template<class T>
void test() {
if (std::is_fundamental<T>::value) {
// ...
} else {
// ...
}
}
// Generic: Not primitive
template<class T>
bool isPrimitiveType() {
return false;
}
... |
580,985 | 589,303 | VS2005 C++ broken vtables | I'm currently working on a quite big (and old, sigh) code base, recently upgraded to VS2005 (SP1). Me and my team are changing/updating/replacing modules in this code as we go but we have occasionally been running into problems where the vtables seems broken. I am no expert on vtables but these sure seems to be broken.... | I found the problem. Silly really but the class hierarchy that caused the problem had a virtual function called GetObject which conflicted with the windows #define with the same name. The header files included these windows header files in different order, which confused the linker. So, in fact the problem was corrupte... |
581,097 | 581,100 | Can I use blocks to manage memory consumption in C++? | I'm trying to gain some memory saving in a C++ program and I want to know if I can use blocks as a scope for variables (as in Perl). Let's say I have a huge object that performs some computations and gives a result, does it makes sense to do:
InputType input;
ResultType result;
{
// Block of code
MyHugeObject... | Yes, you can.
The destructor will be called as soon as the variable falls out of scope and it should release the heap-allocated memory.
|
581,172 | 581,515 | How to use IGlobalInterfaceTable to pass an interface pointer? |
Without:
MFC
ATL
Question:
What are the steps involved, to use IGlobalInterfaceTable, when passing a particular interface pointer to several threads using CreateThread?
| I think this page covers it rather well.
Call RegisterInterfaceInGlobal to put your COM interface in the GIT, pass its cookie to your other threads, which can then call GetInterfaceFromGlobal using that cookie to get the original interface.
Note that each thread has to call CoCreateInstance(CLSID_StdGlobalInterfaceTabl... |
581,204 | 581,369 | How do I check if a user has local admin privileges in win32 | How do I check if a user has local admin privileges in win32 from c++
| Just found IsUserAnAdmin() in shlobj.h which does the job for me.
|
581,209 | 581,708 | How to best write out a std::vector < std::string > container to a HDF5 dataset? | Given a vector of strings, what is the best way to write them out to a HDF5 dataset? At the moment I'm doing something like the following:
const unsigned int MaxStrLength = 512;
struct TempContainer {
char string[MaxStrLength];
};
void writeVector (hid_t group, std::vector<std::string> const & v)
{
... | [Many thanks to dirkgently for his help in answering this.]
To write a variable length string in HDF5 use the following:
// Create the datatype as follows
hid_t datatype = H5Tcopy (H5T_C_S1);
H5Tset_size (datatype, H5T_VARIABLE);
//
// Pass the string to be written to H5Dwrite
// using the address of the pointer!
con... |
581,387 | 581,392 | Valid use of typedef? | I have a char (ie. byte) buffer that I'm sending over the network. At some point in the future I might want to switch the buffer to a different type like unsigned char or short. I've been thinking about doing something like this:
typedef char bufferElementType;
And whenever I do anything with a buffer element I declar... | It is a great (and normal) usage. You have to be careful, though, that, for example, the type you select meet the same signed/unsigned criteria, or that they respond similarly to operators. Then it would be easier to change the type afterwards.
Another option is to use templates to avoid fixing the type till the moment... |
581,426 | 581,446 | Why is a C++ Vector called a Vector? | The question's pretty self-explanatory really. I know vaguely about vectors in maths, but I don't really see the link to C++ vectors.
| Mathematical definition of a vector is a member of the set Sn, which is an ordered sequence of values in a specific set (S). This is what a C++ vector stores.
|
581,548 | 582,275 | C++ Builder runtime error - cannot focus a disabled or invisible window | On main form I have TPageControl and on all of it's tabs I have corresponding Save buttons which are activated on Alt+S combination.
Of course, depending on which tab is opened at the moment, the handler for corresponding Save button should be called; but I get "cannot focus a disabled or invisible window" runtime erro... | You could do it all with one button. In the OnClick handler, check which page is the current one, and call the saving function for that page.
|
581,595 | 581,639 | Vectors, iterators and std::find | Is there any way to use different types of iterators in different vectors? Or, is there a function that returns the position of element in vector as an integer?
std::vector<DWORD>::iterator it; // Iterator
// monsterQueue is a <DWORD> vector
it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), obje... | Try
std::vector<DWORD>::iterator it; // Iterator
// monsterQueue is a <DWORD> vector
it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object);
// Check do we have the object in the queue
if(it != bot.monsterQueue.end()) // If we do have it
{
size_t idx = it - bot.monsterQueue.begin()
... |
581,609 | 581,642 | Looking for an open-source flatfile/xml database C++ library | I'm looking for a light-weight database library that I can compile into a C++ application.
Does any such exist?
| For pure XML embedded database you might want to peek at Oracle Berkeley DB XML.
|
581,773 | 581,789 | Methods of sharing class instances between processes | I have written a C++ class that I need to share an instance of between at least two windows processes. What are the various ways to do this?
Initially I looked into #pragma data_seg only to be disappointed when I realised that it will not work on classes or with anything that allocates on the heap.
The instance of the ... | You can potentially use memory-mapped files to share data between processes. If you need to call functions on your object, you'd have to use COM or something similar, or you'd have to implement your own RPC protocol.
|
582,199 | 582,219 | Assertion error in std:vector used in std::set_difference | I am trying to find the set difference of two vectors, so i do something like this:
std::vector<sha1_hash> first_vec, second_vec, difference_vec;
// populate first_vec and second_vec ...
std::sort(first_vec.begin(),first_vec.end());
std::sort(second_vec.begin(),second_vec.end());
std::set_difference(first_vec.begin(... | Like most c++ algorithms, set_difference does not create new entries in the output vector where none existed before. You ned to create space in the output to hold the results.
Edit: Or use an an insert iterator (following untested):
back_insert_iterator< std::vector<sha1_hash> > bi( difference_vec );
std::set_diffe... |
582,302 | 2,667,045 | Are there optimized c++ compilers for template use? | C++ templates have been a blessing in my everyday work because of its power. But one cannot ignore the (very very very very long) compilation time that results from the heavy use of templates (hello meta-programming and Boost libraries). I have read and tried quite a lot of possibilities to manually reorganize and modi... | It seems that g++ 4.5 has made tremendous progress dealing with templates. Here are the two unavoidable changes.
"When printing the name of a class template specialization, G++ will now omit any template arguments which come from default template arguments." That could be considered a subtle modification, but it will ... |
582,331 | 582,456 | Is there a way to instantiate objects from a string holding their class name? | I have a file: Base.h
class Base;
class DerivedA : public Base;
class DerivedB : public Base;
/*etc...*/
and another file: BaseFactory.h
#include "Base.h"
class BaseFactory
{
public:
BaseFactory(const string &sClassName){msClassName = sClassName;};
Base * Create()
{
if(msClassName == "DerivedA")
{
... | Nope, there is none, unless you do the mapping yourself. C++ has no mechanism to create objects whose types are determined at runtime. You can use a map to do that mapping yourself, though:
template<typename T> Base * createInstance() { return new T; }
typedef std::map<std::string, Base*(*)()> map_type;
map_type map;... |
582,878 | 582,886 | Why is boost so heavily templated? | There are many places in boost where I see a templated class and can't help but think why the person who wrote it used templates.
For example, the mutex class(es). All the mutex concepts are implemented as templates where one could simply create a few base classes or abstract classes with an interface that matches the ... | Templates can be highly optimized at compile time, without the need for virtual functions. A lot of template tricks can be thought of as compile-time polymorphism. Since you know at compile time which behaviours you want, why should you pay for a virtual function call everytime you use the class. As a bonus, a lot o... |
582,879 | 611,360 | Converting OpenGL Primitives to OpenGLES | I'm trying to convert the following code from OpenGL 1.5 spec. to the OpenGLES 1.1 spec
(num_x and num_y are passed into the function by arguments)
::glBegin(GL_LINES);
for (int i=-num_x; i<=num_x; i++)
{
glVertex3i(i, 0, -num_y);
glVertex3i(i, 0, num_y);
}
for (int i=-num_y; i<=num_y; i++)
{
glVertex... | I can see several things wrong with your converted code:
1.- Using the wrong type for the variable verticies, it should be:
GLfloat* verticies = new float[iNumOfVerticies];
2.- Incorrectly filling verticies, second loop should be:
for(int i=-num_y; j < iNumOfVerticies && i<=num_y;i++,j+=6)
{
verticies[j] = -num_x;... |
583,003 | 583,019 | overloading new/delete | I'm making a little memory leak finder in my program, but
my way of overloading new and delete (and also new[] and delete[])
doesn't seem to do anything.
void* operator new (unsigned int size, const char* filename, int line)
{
void* ptr = new void[size];
memleakfinder.AddTrack(ptr,size,filename,line);
retur... | void* ptr = new void[size];
Can't do that. Fix it.
Never ever try to overload new/delete globally. Either have them in a base class and derive all your objects from this class or use a namespace or a template allocator parameter. Why, you may ask. Because in case your program is more than a single file and using STL o... |
583,056 | 583,082 | ATL Collection of non-trivial objects | I would like to expose an ATL COM collection of CMainClass objects
such that it can be accessed by a C#, VB, or C++ client.
I don't have a problem setting up the collection itself, but I don't
know how to allow the COM clients access to classes A, B, and C.
Should I make A, B, & C COM objects with the ones containing a... | Google for implementing IEnumVARIANT in ATL.
Here are some promising links.
http://msdn.microsoft.com/en-us/library/3stwxh95.aspx
http://www.codeguru.com/cpp/com-tech/atl/misc/article.php/c29
Hope this helps.
Responding to your comment:
Yes. If you want to expose Automation Compatible interfaces, i.e. those that can be... |
583,076 | 583,104 | C/C++ changing the value of a const | I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to replicate it I'm not being able to put it to compile.
The concept was that it is possible to change by accident the value of a const in C/C++
It was som... | you need to cast away the constness:
linux ~ $ cat constTest.c
#include <stdio.h>
void modA( int *x )
{
*x = 7;
}
int main( void )
{
const int a = 3; // I promisse i won't change a
int *ptr;
ptr = (int*)( &a );
printf( "A=%d\n", a );
*ptr = 5; // I'm a liar, a is no... |
583,255 | 583,271 | Is it a good practice to place C++ definitions in header files? | My personal style with C++ has always to put class declarations in an include file, and definitions in a .cpp file, very much like stipulated in Loki's answer to C++ Header Files, Code Separation. Admittedly, part of the reason I like this style probably has to do with all the years I spent coding Modula-2 and Ada, bot... | Your coworker is wrong, the common way is and always has been to put code in .cpp files (or whatever extension you like) and declarations in headers.
There is occasionally some merit to putting code in the header, this can allow more clever inlining by the compiler. But at the same time, it can destroy your compile tim... |
583,786 | 681,550 | Why do I get an amibguity error when I compile from the command line, but not from the IDE? | I am trying to compile a rather large project with Borland C++ Builder 5.5. The project compiles in the IDE, but is much too slow. However, when I compile with the command line I get an ambiguity error that was not present in the IDE:
Error E2015 Project.h 536: Ambiguity between 'TTreeNode' and 'Comctrls::TTreeNode'
... | I believe the problem lies in the fact the command line compiler and the IDE compiler are different. The command line appears to be more strict about ambiguity whereas the IDE flags it only as a warning. In light of this, I guess some projects simply can't be built with the command line tools even if they build in th... |
583,821 | 583,898 | How do I return hundreds of values from a C++ function? | In C++, whenever a function creates many (hundreds or thousands of) values, I used to have the caller pass an array that my function then fills with the output values:
void computeValues(int input, std::vector<int>& output);
So, the function will fill the vector output with the values it computes. But this is not real... | Response to Edit: Well, if you need to return hundreds and thousands if values, a tuple of course would not be the way to go. Best pick the solution with the iterator then, but it's best not use any specific iterator type.
If you use iterators, you should use them as generic as possible. In your function you have use... |
583,955 | 584,022 | Connecting to an mssql server from a remote machine gives Login failed for user '' | I get this error when I try to connect to a remote SQL server using this connection string.
Error:
ODBC error:
28000118452[Microsoft][ODBC SQL Server
Driver][SQL Server]Login failed for
user ''. The user is not associated
with a trusted SQL Server connection.
Connection string:
"DRIVER={SQL
Server};SERVER=... | Thoughts:
1.) are both machines in the same domain? I am thinking probably so because of your references to making a connection with WNet*...
If not, Integrated Security will give you problems.
Edit: I see that both machines are not in the same domain. To use Integrated Security, the domain that the SQL Server is in ... |
583,978 | 584,109 | Is it possible to get a valid token from a remote computer? | Is it possible to impersonate a u/p on a remote computer?
Ideally I would like to call the ImpersonateLoggedOnUser with a token I would obtain from logging into a remote computer.
I know I can make a valid connection using wnet functions, but just don't know about impersonation.
| Brian:
I'm not sure whether you can. At the very least, you may need some way to indicate which logged on user (fast user switching and terminal services means that there may be more than one logged on user). Raymond Chen blogged about this once, but there was no solution offered (I'm not sure if there is one, unless... |
584,041 | 584,077 | How do I build an import library (.lib) AND a DLL in Visual C++? | I want to have a single Visual Studio project that builds a DLL file and an import library (.lib) file. (An import library is a statically-linked library that takes care of loading that DLL file in other projects that use it).
So I went to Visual Studio C++ 2008 Express Edition, created a New Project of type Class Lib... | By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.
Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.
You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route... |
584,388 | 584,397 | C++ Library for modifying a ZIP file in place | I'm looking for a way to add or remove files to/from an existing ZIP archive, or any other archive format for that matter as long as there are cross platform APIs, without having to rewrite a new zip file with new files added to it, or sans items deleted from it.
With ZIP files, the catalog is placed at the end of th... | Zipios++ provides direct access to files inside ZIP archives.
|
584,503 | 584,509 | Different methods to use a class/struct - C++ | struct Foo
{
void SayHello()
{
std::cout << "Hi, I am Foo";
}
};
I have the above given struct. I have seen a usage like this in one of our code base.
Foo foo;
{
foo.SayHello();
}
IMO, It does same like
Foo foo;
foo.SayHello();
Or is there any advantage/difference for the first method?
Any t... | In that particular case, it looks quite strange and like a candidate for review. Can be useful in other cases:
Foo foo;
{
ReturnValue v = foo.SayHello();
Send(v);
}
...
Where it would limit the scope of v. One common use is to make the objects in it destroy earlier. Classes that do special stuff in their const... |
584,544 | 586,051 | Are there alternatives to polymorphism in C++? | The CRTP is suggested in this question about dynamic polymorphism. However, this pattern is allegedly only useful for static polymorphism. The design I am looking at seems to be hampered speedwise by virtual function calls, as hinted at here. A speedup of even 2.5x would be fantastic.
The classes in question are sim... | I agree with m-sharp that you're not going to avoid runtime polymorphism.
If you value optimisation over elegance, try replacing say
void invoke_trivial_on_all(const std::vector<Base*>& v)
{
for (int i=0;i<v.size();i++)
v[i]->trivial_virtual_method();
}
with something like
void invoke_trivial_on_all(const std::v... |
584,599 | 584,611 | When is it appropriate to use C++ exceptions? | I'm trying to design a class that needs to dynamically allocate some memory..
I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of me... | Assuming you are using new to allocate memory, and are not overriding the new operator, it will automatically throw the std::bad_alloc exception if it fails to allocate memory properly.
I read somewhere that exceptions
should only be used for "exceptional"
cases, and running out of memory
doesn't seem like an ex... |
584,734 | 584,743 | Gui toolkits, which should I use? | I am writing a fairly large and complex data analysis program and I have reached the point where I think it is about time to build a GUI for the program. So my question is:
Which GUI toolkit should I use?
I am completely new to coding and building GUIs and would appreciate any guidance that can be offered. It doesn't h... | For C++, in my opinion, Qt is the least frustrating and most fully featured toolkit. Its also fully cross platform. Note that Qt will be LGPL licensed some time in March 2009, when version 4.5 becomes available. Currently, its only offered in a GPL and commercial license version.
Qt's GUI designer is good. It has lots... |
584,824 | 584,835 | Guaranteed lifetime of temporary in C++? | Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here's an example class:
class StringBuffer
{
public:
StringBuffer(std::string & str) : m_str(str)
{
m_buffer.push_back(0);
}
~StringBuffer()
{
m... | The destructor for that sort of temporaries is called at the end of the full-expression. That's the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice.
It's in fact what makes expression templates work: ... |
584,825 | 585,298 | dSYM Directories While Compiling C++ Code in MacOS | Why compiling C++ in Mac always create *.dSYM directories?
Is there a way to disable that?
| It's because your Xcode project is set up to build debug symbols with an external dSYM file. This is actually very handy for release builds, as it means that you can strip debug symbols from your app, and when a user sends a crashdump to you, you can use the original dSYM file to generate a proper stacktrace for debug... |
585,257 | 585,274 | Is there a better way to reverse an array of bytes in memory? | typedef unsigned char Byte;
...
void ReverseBytes( void *start, int size )
{
Byte *buffer = (Byte *)(start);
for( int i = 0; i < size / 2; i++ ) {
std::swap( buffer[i], buffer[size - i - 1] );
}
}
What this method does right now is it reverses bytes in memory. What I would like to know is, is th... | The standard library has a std::reverse function:
#include <algorithm>
void ReverseBytes( void *start, int size )
{
char *istart = start, *iend = istart + size;
std::reverse(istart, iend);
}
|
585,351 | 585,360 | running msbuild without having VS installed | I'm trying to run msbuild on a solution that has some C++ code in it.
I have the SDK installed but not Visual Studio.
I get the following error:
error MSB3411: Could not load the Visual C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 an... | It might be as simple as vcbuild.exe not being in the path. IIRC, at least the visual studio installer doesn't automatically add the command line tools to the system or user path and you have to run vcvars32.bat to set them first before you can kick off the build.
|
585,913 | 585,932 | C++ member function virtual override and overload at the same time | If I have a code like this:
struct A {
virtual void f(int) {}
virtual void f(void*) {}
};
struct B : public A {
void f(int) {}
};
struct C : public B {
void f(void*) {}
};
int main() {
C c;
c.f(1);
return 0;
}
I get an error that says that I am trying to do an invalid conversion from int to void*. W... | The short answer is "because that's how overload resolution works in C++".
The compiler searches for functions F inside the C class, and if it finds any, it stops the search, and tries to pick a candidate among those. It only looks inside base classes if no matching functions were found in the derived class.
However, y... |
586,009 | 595,677 | Inheritance issues with template classes | I'm having issues with a very strange error in some code I wrote.
The basic idea behind the code can be trivialised in the following example:
template <class f, class g> class Ptr;
template <class a, class b, class c = Ptr<a,b> >
class Base
{
public:
Base(){};
};
template <class d, class e>
class Derived : pub... | Unfortunately, I was being slightly stupid and had forgotten to put my Ptr class in the same namespace as the Base and Derived classes.
That, I guess, would be why it wasn't working ! =]
|
586,410 | 586,439 | Table layout using std::cout | How do I format my output in C++ streams to print fixed width left-aligned tables? Something like
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
poducing
12345.123 12345.123
| Include the standard header <iomanip> and go crazy. Specifically, the setw manipulator sets the output width. setfill sets the filling character.
|
586,609 | 586,670 | Using SSE instructions | I have a loop written in C++ which is executed for each element of a big integer array. Inside the loop, I mask some bits of the integer and then find the min and max values. I heard that if I use SSE instructions for these operations it will run much faster compared to a normal loop written using bitwise AND , and if... |
SSE instructions are processor specific. You can look up which processor supports which SSE version on wikipedia.
If SSE code will be faster or not depends on many factors: The first is of course whether the problem is memory-bound or CPU-bound. If the memory bus is the bottleneck SSE will not help much. Try simplifyi... |
586,727 | 586,837 | What approach works best for quickly reading files off of optical drives? | When reading files off of a hard drive, mmap is generally regarded as a good way to quickly get data into memory. When working with optical drives, accesses take more time and you have a higher latency to worry about. What approach/abstraction do you use to hide/eliminate as much latency and/or overall load time of the... | There's no real abstraction you can employ. Optical drives have very specific characteristics that must be optimized for to get the best performance.
Some tips:
The biggest killer on optical drives is seek time. Where possible make sure all the files you are reading are sequential on disc and as closely packed as possi... |
586,734 | 586,831 | Pass an element from C type string array to a COM object as BSTR? (in C++) | I am writing a C++ DLL that is called by an external program.
1.) I take an array of strings (as char *var) as an argument from this program.
2.) I want to iterate through this array and call a COM function on each element of the string array. The COM function must take a BSTR:
DLL_EXPORT(void) runUnitModel(char *rate... | If you're using Microsofts ATL, you can use the CComBSTR class.
It will accept a char* and create a BSTR from it, also, you don't need to worry about deleting the BSTR, all that happens in the dtor for CComBSTR.
Also, see Matthew Xaviers answer, it doesn't look like you're passing your array of strings into that functi... |
587,070 | 587,116 | C++ constructor syntax | Simple question: are the following statements equivalent? or is the second one doing more implicit things behind the scenes (if so, what?)
myClass x(3);
myClass x = myClass(3);
Thanks!
| They are not completely identical. The first is called "direct initialization" while the second is called "copy initialization".
Now, the Standard makes up two rules. The first is for direct initialization and for copy initialization where the initializer is of the type of the initialized object. The second rule is fo... |
587,128 | 587,139 | What exactly is va_end for? Is it always necessary to call it? |
va_end - Macro to reset arg_ptr.
After accessing a variable argument list, the arg_ptr pointer is usually reset with va_end(). I understand that it is required if you want to re-iterate the list, but is it really needed if you aren't going to? Is it just good practice, like the rule "always have a default: in your sw... | va_end is used to do cleanup. You don't want to smash the stack, do you?
From man va_start:
va_end()
Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function. After the call va_end(ap) the variable ap is undefined. Multiple traversals of the list, each bracketed by... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.