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 |
|---|---|---|---|---|
281,045 | 281,082 | Do class/struct members always get created in memory in the order they were declared? | This is a question that was sparked by Rob Walker's answer here.
Suppose I declare a class/struct like so:
struct
{
char A;
int B;
char C;
int D;
};
Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing? I'm asking because I ha... | C99 §6.7.2.1 clause 13 states:
Within a structure object, the
non-bit-field members and the units in
which bit-fields reside have addresses
that increase in the order in which
they are declared.
and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1.
C++ is a bit more ... |
281,060 | 281,822 | Win32 WriteProcessMemory() magical offset value | I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "mag... | Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of shared memory, and I did a quick check to make sure these functions are supported by Windows Mobile 5.
|
281,136 | 281,266 | Creating an object in shared memory inside a Shared Lib (so) in C++ | Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object?
god* _god = NULL;
extern "C"
{
int set_log_level(int level)
{
if(_god == NULL) return -1;
_stb->log_level(level);
return 0;
}
int god_init(){
if(_god == NULL){
_god = new g... | Boost Interprocess library has high(er) level, portable shared memory objects.
|
281,260 | 281,379 | RGB back buffer in Win32 | I have an array of RGB values, whose size I can guarantee to match the client area of a window on screen.
Using the Win32 API, what are the easiest and fastest ways to get the contents of my array on the screen in response to a WM_PAINT message?
If it makes it simpler/faster, we can assume it's a 32-bit display and eac... | If you have complete control over your backing format, use a DIB format and a dummy BITMAPINFO structure. Then use SetDIBitsToDevice to copy to the DC.
Be aware of the peculiarities of the DIB format - every line has to be extended to a multiple of 4 bytes, the first line of the buffer is the bottom line of the image, ... |
281,275 | 281,296 | Best way to merge multiple STL containers, removing duplicate elements? | I have two STL containers that I want to merge, removing any elements that appear more than once. For example:
typedef std::list<int> container;
container c1;
container c2;
c1.push_back(1);
c1.push_back(2);
c1.push_back(3);
c2.push_back(2);
c2.push_back(3);
c2.push_back(4);
container c3 = unique_merge(c1, c2);
// c... | For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N*log n).
The other option is to run std::sort on each list individually and then walk through them in parallel using std::set_union, which removes d... |
281,365 | 281,385 | Does myVector.erase(myPtr) delete the object pointed by myPtr? | If I have the following code,
Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);
Did I create a memory leak?
I guess so, but the word erase gives the feeling that it is deleting it.
Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you thi... | Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.
It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the cont... |
281,445 | 281,502 | Namespacing (static) member variables | I would like to be able to achieve something like this:
class Zot
{
namespace A
{
static int x;
static int y;
}
}
I am working with a legacy system that uses code generation heavily off a DB schema, and certain fields are exposed as methods/variables in the class definition. I need to ... | Really the inner struct is your best bet. Another possibility would be to use a typedef to bring in a class of statics. This works well for code generation in that you can separate the extras from the generated code:
In the generated file that doesn't care at all what's in Zot_statics:
class Zot_statics;
class Zo... |
281,698 | 281,707 | What is wrong with this inheritance? | I just don't get it. Tried on VC++ 2008 and G++ 4.3.2
#include <map>
class A : public std::multimap<int, bool>
{
public:
size_type erase(int k, bool v)
{
return erase(k); // <- this fails; had to change to __super::erase(k)
}
};
int main()
{
A a;
a.erase(0, false);
a.erase(0); // <- f... | When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should stop looking for the function you are trying to call once it finds the first match. After finding the function by name, then it applies the overload resoluti... |
281,725 | 281,830 | Template specialization based on inherit class | I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.
-edit-
I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them.
class SomeTag {};
class InheritSomeTag : public SomeTag {};
template ... | This article describes a neat trick: http://www.gotw.ca/publications/mxc++-item-4.htm
Here's the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking):
template<typename D, typename B>
class IsDerivedFrom
{
class No { };
class Yes { No no[3]; };
static Yes Test( B* ... |
281,787 | 281,807 | Best way to take a snapshot of an object to a file | What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that... | Take a look at this library .
|
281,818 | 4,541,470 | Unmangling the result of std::type_info::name | I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector<... | Given the attention this question / answer receives, and the valuable feedback from GManNickG, I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features.
In file type.hpp
#ifndef TYPE_HPP
#define TYPE_HPP
#include <string>
#include <typeinfo>
std... |
282,016 | 282,560 | Using C++ COM interface in C# for both client and server | I need to make a piece of C# code interact through COM with all kinds of implementations.
To make it easeier for users of that integration, I included the interacted interfaces in IDL (as part of a relevant existing DLL, but without coclass or implementation), then got that into my C# code by running Tlbimp to create t... | Again - thanks for the suggestions.
I was able to finally resolve the issue on my own. I tried the above suggestions and didn't made any progress. Then I changed the namespace of the interop in the 'testing' code - it varied from the one in the main code because of different argument use when using Tlbimp. This solved ... |
282,091 | 282,442 | Set OLE Request Timeout from C++ | I am instantiating a local COM server using CoCreateInstance. Sometimes the application providing the server takes a long time to start. When this happens, Windows pops a dialog box like this:
Server Busy
The action cannot be completed because the other program is busy. Choose 'Switch To' to activate the busy program... | If you're using MFC, we used to do stuff like this:
// prevent the damned "Server Busy" dialog.
AfxOleGetMessageFilter()->EnableBusyDialog(0);
AfxOleGetMessageFilter()->EnableNotRespondingDialog(0);
|
282,176 | 282,190 | Waitpid equivalent with timeout? | Imagine I have a process that starts several child processes. The parent needs to know when a child exits.
I can use waitpid, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in waitpid to exit gracefully and join it. It's nice to have things clean up themselves, but it may ... | The function can be interrupted with a signal, so you could set a timer before calling waitpid() and it will exit with an EINTR when the timer signal is raised. Edit: It should be as simple as calling alarm(5) before calling waitpid().
|
282,194 | 282,220 | How to get memory usage under Windows in C++ | I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.
| A good starting point would be GetProcessMemoryInfo, which reports various memory info about the specified process. You can pass GetCurrentProcess() as the process handle in order to get information about the calling process.
Probably the WorkingSetSize member of PROCESS_MEMORY_COUNTERS is the closest match to the Mem ... |
282,372 | 3,453,616 | demote boost::function to a plain function pointer | want to pass boost::bind to a method expecting a plain function pointer (same signature).
typedef void TriggerProc_type(Variable*,void*);
void InitVariable(TriggerProc_type *proc);
boost::function<void (Variable*, void*)> triggerProc ...
InitVariable(triggerProc);
error C2664: 'InitVariable' : cannot convert parameter... | Has anyone noticed that the accepted answer only works with trivial cases? The only way that function<>::target() will return an object that can be bound to a C callback, is if it was constructed with an object that can be bound to a C callback. If that's the case, then you could have bound it directly and skipped all ... |
282,419 | 284,681 | How to create an alias for a build target with a relative path in Scons? | Background
I'm trying out Scons by setting up a basic C++ sample project that has two sub-projects:
Prj1 is an EXE that depends on Prj2
Prj2 is a DLL that exports some functions
You can see the directory structure and the contents of my SConstruct and SConscript files here
Problem
The problem I'm running into is that... | Moving this to an answer instead of a comment. :)
References
How
do I get projects to place their
build output into the same directory
with Scons?
Alias needs an actual target as its second argument. I think the issue is that "project1" (the value of PROG) is not an actual target. An easy way to correct this is the f... |
282,526 | 282,553 | Commenting out comments | I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example:
If I have:
/*
int commented_out = 0;
*/
I can comment out the /* and */ with // and code within the /* and */ is no longer "commented out" (the text changes to non-comment color a... | Yep, this is perfectly normal behavior. The C++ standard says that a /* is the start of a comment block only if it itself is not commented out. I often use what you've written above to comment or uncomment a block of code by adding/deleting one character. A nice little trick for switching between two blocks of code,... |
282,570 | 282,573 | C++ Opening a file and inputting data to a class object | Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way.
I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user... | It looks like it will work fine, and I would say this is probably the best way to do it. But why are you asking here instead of just testing it yourself?
|
282,603 | 282,658 | C++ compiler optimization of passed arguments | I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:
WARN(
"Danger Will Robinson! There are "
+ boost::lexical_cast<string>(minutes)
+ " minutes of oxygen left!"
);
I'm using an inline function for WARN, but I'm curious as to how much optimiz... | If you need to be able to selectively enable and disable the warnings at run-time, the compiler will not be able to optimize out the call.
What you need is to rename your function to WARN2 and add a macro something like:
#define WARN(s) do {if (WARNINGS_ENABLED) WARN2(s);} while (false)
This will prevent the evaluatio... |
282,696 | 282,725 | How to call c++ binary from Perl or PHP (CGI-BIN using Apache on Linux )? | I have a website cgi-bin program that is written in c++.
Unfortunately the website provider for my friend's site only allows Perl or PHP cgi-bin scripts.
Is there an easy way to simply have a very small Perl or PHP wrapper that just calls the c++ compiled binary?
Would the c++ program still be able to read from stdin... | You can use Perl's backticks or "system" commands to run shell commands. Also, perl has a lot of "Inline" classes that allow you to write code in other languages to be called in perl, including one for C++. If you can't find something that works, maybe you can make your own wrapper using that package.
|
282,700 | 282,717 | ld: duplicate symbol | I'm working on a school project and I'm getting some weird errors from Xcode. I'm using TextMate's Command+R function to compile the project. Compilation seems to work okay but linking fails with an error message I don't understand.
ld output:
ld: duplicate symbol text_field(std::basic_istream >&)in /path/final/build... | My first thought was that you're including it twice on the linker command but it appears to be complaining about having the same function in main.o and generics.o.
So it looks like you're including the io_functions.cpp file into the main.cpp and generics.cpp which is a bad idea at the best of times.
You should have a h... |
282,800 | 282,818 | C++ odd compile error: error: changes meaning of "Object" from class "Object" | I don't even know where to go with this. Google wasn't very helpful. As with my previous question. I'm using TextMate's Command+R to compile the project.
game.h:16:error: declaration of ‘Player* HalfSet::Player() const’
players.h:11:error: changes meaning of ‘Player’ from ‘class Player’
game.h:21:error: ‘Player’ is no... | In C++ you cannot name a function the same name as a class/struct/typedef. You have a class named "Player" and so the HalfSet class has a function named "Player" ("Player *Player()"). You need to rename one of these (probably changing HalfSet's Player() to getPlayer() or somesuch).
|
282,966 | 284,871 | Using Chromium as a MFC CWnd | I am looking to using Google Chromium for my MFC app as an HTML renderer. I found this test bed application and I am wondering if anyone knows how or of a resource that I can make sense of it so that I could extract the Webkit/Webview stuff into my application. Thanks.
~/webkit/tools/test_shell
~/webkit/tools/test/r... | #chromium on irc.freenode.net
http://groups.google.com/group/chromium-dev
|
283,042 | 283,611 | How to pass large struct back and forth between between C++ and Lua | I am looking at embedding Lua in a C++ application I am developing. My intention is to use Lua to script what ordered operation(s) to perform for some given input, ie.
receive a new work item in c++ program, pass details to Lua backend, Lua calls back into c++ to carry out necessary work, returns finished results.
The... | If I recall correctly, light userdata is actually just a pointer. They all share the same metatable. They are mostly used to pass around addresses of C data.
Full userdata is probably closer of what you need if you must access it from the Lua side. Their metatable would allow you to access it like it was a regular Lua ... |
283,166 | 283,172 | Easy way to convert a struct tm (expressed in UTC) to time_t type | How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to be in UTC.
| Use timegm() instead of mktime()
|
283,295 | 283,337 | SendMessage API in 64 bit | According to MSDN
The return value specifies the result
of the message processing; it depends
on the message sent.
I know it is defined as
typedef LONG_PTR LRESULT;
Meaning it will be 8 bytes on 64bit machine but it doesn't!
Does anyone know if it is safe to assume that only the lower 4 bytes are used and store... | No it's not safe, because the return value is defined by the message being sent and the handler.
If you control the handler and the message then it'd be possible, it's not safe in the general case.
James
|
283,297 | 283,317 | Return dynamically allocated memory from C++ to C | I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..
const char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
return ss.str().c_str();
}
could the c string be destroyed when ss falls of... | The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug.
Next, yo... |
283,375 | 283,387 | Detecting TCP Client Disconnect | Let's say I'm running a simple server and have accept()ed a connection from a client.
What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle thi... | select (with the read mask set) will return with the handle signalled, but when you use ioctl* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.
This is a great discussion on the various methods of checking that the client has disconnected: Stephen C... |
283,406 | 283,408 | What is the difference between atan and atan2 in C++? | What is the difference between atan and atan2 in C++?
| std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.
|
283,450 | 283,475 | How do you organise your STL headers? | I am working on a large project that uses the STL and have a question about your preferred way to organise your STL #includes.
Do you prefer to #include each header in the source file it is used. For example, if both foo.cpp and bar.cpp require std::string, then both will #include <string>.
Do you prefer to have a si... | I only include the header files that are really needed in every source, and not 'catch all' headers, to keep dependencies (and hence compile times) as low as possible.
Precompiled headers can work irrespective of this (i.e. I rely on precompiled headers to speed up the compiling process, not to get declarations). So ev... |
283,593 | 283,624 | Using C++ from Objective C : how to allocate/deallocate? | Currently, my Objective C classes use C++ objects by doing a new when the owner is created, and calling delete when it is destroyed. But is there another way? I'd like to be able to declare, say, an auto_ptr whose scope lasts the duration of the Objective C class' lifetime.
| Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects)... |
283,646 | 283,693 | STL Migration issues (VS 2003 -> 2005) | I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:
void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );
T... | Your program is incorrect as NULL cannot be converted as an iterator. I don't really know what you want these iterators to be initialized as. If you need an iterator guarantied not to be in a container but to be still "valid", you can use a default-constructor:
typedef std::vector<CSomeObject*> myvector_t;
void SomeFn(... |
283,726 | 283,970 | Memory leak detection under Windows for GNU C/C++ | What memory leak detection tools are available for use with open source C/C++ on Windows?
| The mem (revised) package is an effective and straightforward tool to detect memory buffer overflows, underflows, leaks, double-deletion, and dangling references.
Original link to c.snippets.org, now invalid.
|
284,556 | 284,663 | delete or virtual delete? | I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do
Obj *obj = libname_newDevice();
Now, should I use delete or should I do obj->deleteMe();? I ask because I am not exactly doing new so I ... | I would take one step further.
If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.
class ObjWrap
{
public:
ObjWrap()
:obj(libname_newDevice())
{}
~Obj... |
284,566 | 284,720 | How can you initialize a class with a reference member from a private constructor? | I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler?
struct InterfaceWrapper {
InterfaceWrapper( SomeHugeStructure& src ):m_inte... | As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you.
If the purpose is to limit access to friends of the class, the... |
284,716 | 284,734 | MSXML Select Nodes Not Working | I am working on an automated testing app, and am currently in the process of writing a function that compares values between two XML files that should be identical, but may not be. Here is a sample of the XML I'm trying to process:
<?xml version="1.0" encoding="utf-8"?>
<report xmlns="http://www.**.com/**">
<subrepo... | I'm used to doing this with .NET's XmlDocument objects, but I think the effect is the same here:
If the XML document includes a namespace -- even an unnamed one -- then the Xpath query has to use one as well. So, you'll have to add the namespace to the XMLDoument which you might as well give a name in the code, and th... |
284,833 | 284,859 | How do you declare arrays in a c++ header? | This is related to some other questions, such as: this, and some of my other questions.
In this question, and others, we see we can declare and initialise string arrays in one nice step, for example:
const char* const list[] = {"zip", "zam", "bam"}; //from other question
This can be done in the implementation of a fun... | Use the keyword static and external initialization to make the array a static member of the class:
In the header file:
class DataProvider : public SomethingElse
{
static const char* const mStringData[];
public:
DataProvider();
~DataProvider();
const char* const GetData()
{
int index = GetC... |
285,200 | 285,631 | Can Boost Spirit be used to parse byte stream data? | Can Spirit (part of Boost C++ library) be used to parse out binary data coming from a stream? For example, can it be used to parse data coming from a socket into structures, bytes, and individual bit flags? Thanks!
| Boost Spirit allows for a parser to be defined using Extended Backus–Naur Form (EBNF) syntax with template meta-programming. It is very flexible and uses abstract classes in all phases of the parsing process that can be customized. In order to process a binary data stream, you would need to implement custom scanner cla... |
285,367 | 323,349 | How do I create a filter for Microsoft Excel? | I want to add a file type extension to the Open Dialog of Excel (2003, 2007 if possible, 2007 only, if necessary).
When the user opens my type of file (i.e. myfile.myx), I want my application to read the file and paste the file into Excel in my own defined manner (by using Interop)
| I think you are out of luck here. There is no documented way of extending Excel with custom import filter (as far as I know). Such a converter interface only exists for Word (http://support.microsoft.com/kb/111716).
If you want to modify the file open dialog you could try to subclass the dialog. This works for the Wind... |
285,372 | 285,380 | automatic class templates? | Is there a way to have the compile deduce the template parameter automatically?
template<class T>
struct TestA
{
TestA(T v) {}
};
template<class T>
void TestB(T v)
{
}
int main()
{
TestB (5);
}
Test B works fine, however when i change it to TestA it will not compile with the error " use of class template re... | No, there isn't. Class templates are never deduced. The usual pattern is to have a make_ free function:
template<class T> TestA<T> make_TestA(T v)
{
return TestA<T>(v);
}
See std::pair and std::make_pair, for example.
In C++0x you will be able to do
auto someVariable = make_TestA(5);
to avoid having to specify th... |
285,482 | 296,140 | Using PrintDlg on Vista x64 does not work, works fine on 32 bit and XP | We've got an app with some legacy printer "setup" code that we are still using PrintDlg for. We use a custom template to allow the user to select which printer to use for various types of printing tasks (such as reports or drawings) along with orientation and paper size/source.
It works on XP and 32-bit Vista, but on V... | I found a related post on the Microsoft forums: On Vista x64, DocumentProperties fails from UAC-elevated process
I've verified with a sample program that PrintDlg running as non-admin works.
|
285,551 | 285,574 | How to add a simple API to my C++ application for access by LabView? | I have a data acquisition program written in C++ (Visual Studio 6.0). Some clients would like to control the software from their own custom software or LabView. I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started. This is going to be VERY basic... | You are on the right track with a DLL. The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use. Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your ... |
285,710 | 285,926 | What techniques can you use to profile your code | Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.
The target language is C++.
I am interested in what you have personally used.
| I've found the following quite useful:
#ifdef PROFILING
# define PROFILE_CALL(x) do{ \
const DWORD t1 = timeGetTime(); \
x; \
const DWORD t2 = timeGetTime(); \
std::cout << "Call to '" << #x << "' took " << (t2 - t1) << " ms.\n"; \
}while(false)
#else
# define PROFILE_CALL(x) x
#endif
Which can be us... |
285,886 | 285,894 | In C++ You Can Have a Pointer to a Function, Can you also have a pointer to a class? | I'm not talking about a pointer to an instance, I want a pointer to a class itself.
| In C++, classes are not "first class objects". The closest you can get is a pointer to its type_info instance.
|
286,105 | 286,617 | How to synchronize C & C++ libraries with minimal performance penalty? | I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math opera... | Your wrapper itself will be inlined, however, your method calls to the C library typically will not. (This would require link-time-optimizations which are technically possible, but to AFAIK rudimentary at best in todays tools)
Generally, a function call as such is not very expensive. The cycle cost has decreased consid... |
286,402 | 286,667 | Initializing struct, using an array | I have a couple of array's:
const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"};
const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"};
which i then need to parse out for '=' and then put the value... | This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g.
const string a_strs[] = {"cr=1", "ag=2", "gnd=U", NULL};
Then I would write a (private) helper function that parse the stri... |
286,534 | 286,555 | Enumerating all available drive letters in Windows | I want to enumerate all available drive letters (which aren't already taken) in Windows using VC++.
How can I do this?
| ::GetLogicalDrives() returns a list of available (read: used) drives as bits in a mask. This should include mapped network drives. Thus, you can simply walk the bits to find bits that are zero, meaning no drive is present. If in doubt, you can always call ::GetDriveType() with the drive letter + ":\" (":\\" in C code, ... |
286,606 | 288,447 | Changing Keyboard Layout on Windows Mobile | In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.
Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?
Thanks!
| You don't need to.
Just like full windows, you can set the edit control to be numeric input only. You can either do it manually or in the dialog editor in the properites for the edit control.
The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus.
|
286,677 | 286,895 | What code changes are required to migrate C++ from VS2003 to VS2005? | We are considering moving the win32 build of our cross-platform C++ application from MS Visual Studio 2003 to MS Visual Studio 2005. (Yes, very forward-looking of us ;)
Should we expect to many code changes to get it compiling and working?
| I've just migrated a comparatively large codebase from VS2003 to VS2008 via VS2005 and the majority of issues I found were const/non-const issues like assigning the return value of a function that returns a const char * to char *. Both VS2005 and VS2008 are a lot more picky when it comes to const correctness and if you... |
286,714 | 286,752 | What are the advantages of VS2008 over VS2005 for C++ development? | We are considering switching from MS Visual Studio 2003 to MS Visual Studio 2005 for our C++ development. I think jumping to 2008 might be better.
In what ways are VS2008 better than VS2005 for C++ development?
Are there any disadvantages of VS2008 over VS2005?
| There are very little difference between 2005 and 2008 from native C++ developer point of view. However, if coming from 2003, it makes sense to upgrade directly to 2008 - the conversion process should be almost the same, and you will end up with a slightly better platform. Some new features which are available for 2008... |
287,053 | 287,435 | How to determine video dimensions of an mpeg-2 program stream file | How do I programmatically find out the width and height of the video in an mpeg-2 transport program stream file?
Edit: I am using C++, but am happy for examples in any language.
Edit: Corrected question - it was probably program streams I was asking about
| Check out the source code to libmpeg2, a F/OSS MPEG2 decoder. It appears that the width and height are set in the mpeg2_header_sequence() function in header.c. I'm not sure how control flows to that particular function, though. I'd suggest opening up an MPEG2 file in something using libmpeg2 (such as MPlayer) and at... |
287,259 | 287,265 | minimum c++ make file for linux | I've looking to find a simple recommended "minimal" c++ makefile for linux which will use g++ to compile and link a single file and h file. Ideally the make file will not even have the physical file names in it and only have a .cpp to .o transform. What is the best way to generate such a makefile without diving into th... | If it is a single file, you can type
make t
And it will invoke
g++ t.cpp -o t
This doesn't even require a Makefile in the directory, although it will get confused if you have a t.cpp and a t.c and a t.java, etc etc.
Also a real Makefile:
SOURCES := t.cpp
# Objs are all the sources, with .cpp replaced by .o
OBJS := $(... |
287,379 | 287,521 | Parsing C++ preprocessor #if statements | I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.
I have this implemented and working in Python, but it only handles #ifdef and #ifndef stateme... | As KeithB said, you could just let the preprocessor do this for you.
But if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper #define directives in a header... |
287,702 | 287,723 | Executable reading itself | I need to read data added to the end of an executable from within that executable .
On win32 I have a problem that I cannot open the .exe for reading. I have tried CreateFile and std::ifstream.
Is there a way of specifying non-exclusive read access to a file that wasn't initially opened with sharing.
EDIT- Great thing ... | Why not just use resources which are designed for this functionality. It won't be at the end, but it will be in the executable.
If you are adding to the .exe after it is built -- you don't have to add to the end, you can update resources on a built .exe
http://msdn.microsoft.com/en-us/library/ms648049(VS.85).aspx
|
288,034 | 288,050 | randomness algorithm | I need some help regarding algorithm for randomness. So Problem is.
There are 50 events going to happen in 8 hours duration. Events can happen at random times.
Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736.
How can I do this with random generation algorithm?
I can get random ... |
Create a list of 50 numbers.
Fill them with a random number between 1 and 8 * 60 * 60.
Sort them
And you have the 50 seconds.
Note that you can have duplicates.
|
288,038 | 288,071 | How to safely escape a string from C++ | I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes.
Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping.
Is there a function available in ... | There isn't a single solution that works everywhere because different shells have different ideas of what special characters are and how they are interpreted. For bash, you could probably get away with surrounding the entire filename in single quotes after replacing every single quote in the file name with '"'"' (the ... |
288,102 | 288,241 | calculate seconds-to-date for pre-epoch date/times using MS VS2003 | I have this routine that calculates the seconds-to-date for a struct tm. On Linux my implementation using mktime works fine, but
mktime on windows VS2003/.NET 1.1 returns -1 for pre-epoch datetimes.
How do I calculate meaningful time_t values (i.e.
value + secondsToEpoch == secondsToDatetime
) from a for pre-epoch ... | Looking at a couple of mktime sources on the net, they all look pretty portable so you ought to be able to grab one and just put it in your source, paying attention to legal requirements, of course.
That said, I think you have to look for the right one. What dates are you working with? If you're working with pre-1970... |
288,178 | 288,311 | Lambda expression exercise | I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...
is there a way to simplify a c++ integration function like this:
// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
fo... | What about this:
public double Integrate(double a,double b, Func<double, double> f)
{
double sum = 0.0;
for (int n = 0; n <= 100; ++n)
{
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
Test:
Func<double, double> fun = x => Math.Pow(x,2); ... |
288,217 | 288,233 | Forcing something to be destructed last in C++ | I am working on a C++ app which internally has some controller objects that are created and destroyed regularly (using new). It is necessary that these controllers register themselves with another object (let's call it controllerSupervisor), and unregister themselves when they are destructed.
The problem I am now facin... | You could use the Observer pattern. A Controller communicates to it's supervisor that it's being destroyed. And the Supervisor communicates the same to it's child upon destruction.
Take a look at http://en.wikipedia.org/wiki/Observer_pattern
|
288,282 | 292,962 | How does VC++ mangle local static variable names? | Here's some code I have:
MyClass* MyClass::getInstance()
{
static MyClass instance;
return &instance;
}
I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there t... | Well, the function-scoped static instance variable doesn't show up in a .map file generated by cl.exe /Fm, and it doesn't show up when I use x programname!*MyClass* in WinDbg, so the mangled name doesn't seem to contain MyClass at all.
Option 1: Disassemble MyClass::getInstance
This approach seems easier:
0:000> uf pr... |
288,465 | 289,207 | How can I access element attributes from an IXMLDOMNode? | I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node?
Part of me wants to downcast the Node to an... | I don't see anything wrong with what you have written.
The smart com pointers will help you convert if they can, you don't have to write the query interface yourself.
MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMElementPtr pParentElement( pParentNode );
Using the P... |
288,739 | 20,136,256 | Generate random numbers uniformly over an entire range | I need to generate random numbers within a specified interval, [max;min].
Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.
Currenly I am generating as:
for(int i=0; i<6; i++)
{
DWORD random = rand()%(max-min+1) + min;
}
From my tests, random numbers are... | Why rand is a bad idea
Most of the answers you got here make use of the rand function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX), and is therefore discouraged.
C++11 and generation over a range
With C++11 multiple other options have risen... |
289,157 | 289,218 | How can I pass a reference parameter (&) (not pointer) using p/invoke in C#? | I have a C++ API prototype
void Func(int& size);
How can I translate it to P/Invoke in C#?
From what I know, if I use
public static extern Func(ref int size);
, the function will receive a pointer to the int instead of the value.
| (Ooops... meant this as an answer, not a comment).
And when you call it from C++, the function will receive a pointer also. How else do you think references are implemented? Func() will treat that pointer as a reference, so how it gets there isn't important.
|
289,381 | 289,404 | Strange issue running infinite while loop in EXE | I am facing strange issue on Windows CE:
Running 3 EXEs
1)First exe doing some work every 8 minutes unless exit event is signaled.
2)Second exe doing some work every 5 minutes unless exit event signaled.
3)Third exe while loop is running and in while loop it do some work at random times.
This while loop continues until... | Put the while loop in the third EXE to Sleep each time through the loop and see what happens. Even if it doesn't fix this particular probem, it isn't ever good practice to poll with a while loop, and even using Sleep inside a loop is a poor substitute for a proper timer.
|
289,389 | 289,391 | What happens to namespace? | when a dll is created out of the source code in a given namespaces a,b with functions a::open,b::open will there be any conflict in calling these function.
| No, because the function names exported from the DLLs are the C++ mangled names. The mangled names include the namespace, so there will be no conflict.
|
289,397 | 289,407 | How are DLLs created out of C++ source, and how are they used in other sources? | How are DLLs created out of C++ source code, and how are they used in other sources?
| The DLL is a 'Dynamic Link Library' which works a lot like other libraries but is not linked with your executable application. At run time you can call specific functions for loading your DLL and executing its exported methods.
You can try creating a DLL yourself- create a project using visual studio and specify a DLL... |
289,559 | 289,671 | Class layout in C++: Why are members sometimes ordered? | The C++ standard dictates that member variables inside a single access section must be layed out in memory in the same order they were declared in. At the same time, compilers are free to choose the mutual ordering of the access sections themselves. This freedom makes it impossible in theory to link binaries created ... |
This freedom makes it impossible in theory to link binaries created by different compilers.
It's impossible for a number of reasons, and structure layout is the most minor. vtables, implementations of operator new and delete, data type sizes...
So what are the remaining reasons for the strict in-section ordering?
C... |
289,568 | 290,250 | Can C++ access sections be interleaved? | The C++ standard imposes an ordering on class member variables in memory. It says that the addresses of member variables have to increase in the order of declaration, but only inside one access section. Very specifically, this does not seem to prevent compilers from laying out access sections in an interleaved way. ... | I checked out the C++ standard. In section 9.2, paragraph (or clause or whatever) 12, it says "The order of allocation of nonstatic data members separated by an access-specifier is unspecified." "Unspecified" means implementation-dependent behavior that need not be documented.
Therefore, the standard is explicitly sa... |
289,715 | 289,747 | Last key in a std::map | I am looking for the highest key value (a defined by the comparison operator) of a std::map.
Is this guaranteed to be
map.rbegin()->first
?
(I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map)
If not, please advise. I cannot change the data structure.
| Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.
[Edit: as Charles Bailey points out in his answer, your code gives the greatest key if it exists - i.e. if the map is non-empty]
|
289,779 | 294,549 | Calculating a boundary around several linked rectangles | I am working on a project where I need to create a boundary around a group of rectangles.
Let's use this picture as an example of what I want to accomplish.
EDIT: Couldn't get the image tag to work properly, so here is the full link:
http://www.flickr.com/photos/21093416@N04/3029621742/
We have rectangles A and C who ... | Using the example, where rectangles are perpendicular to each other and can therefore be presented by four values (two x coordinates and two y coordinates):
1 2 3 4 5 6
1 +---+---+
| |
2 + A +---+---+
| | B |
3 + + +---+---+
| | | | |
4 +---+---+---+... |
289,838 | 289,903 | Posting to a URL with wxWidgets | Does anyone have some sample code showing how to POST to a URL using wxWidgets? The documentation and discussion forums imply that it's possible but the methods in wxHTTP are very low-level compared to what you find in .NET and scripting languages like Perl and Ruby. Do I actually have to create the HTTP request myself... | I came across a similar problem initially and ended up using Curl instead as it's also cross platform and is very easy to use.
Tim
|
290,034 | 293,219 | Is there a way to use pre-compiled headers in VC++ without requiring stdafx.h? | I've got a bunch of legacy code that I need to write unit tests for. It uses pre-compiled headers everywhere so almost all .cpp files have a dependecy on stdafx.h which is making it difficult to break dependencies in order to write tests.
My first instinct is to remove all these stdafx.h files which, for the most part,... | Yes, there is a better way.
The problem, IMHO, with the 'wizard style' of precompiled headers is that they encourage unrequired coupling and make reusing code harder than it should be. Also, code that's been written with the 'just stick everything in stdafx.h' style is prone to be a pain to maintain as changing anythin... |
290,038 | 290,048 | Is the return type part of the function signature? | In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.
| Normal functions do not include the return type in their signature.
(note: i've rewritten this answer, and the comments below don't apply to this revision - see the edit-history for details).
Introduction
However, the matter about functions and function declarations in the Standard is complicated. There are two layers ... |
290,139 | 290,264 | Event Handler for Minimize and Maximize Window | I am developing an application for PocketPC. When the application starts the custom function SetScreenOrientation(270) is called which rotates the screen. When the application closes the function SetScreenOrientation(0) is called which restores the screen orientation.
This way the screen orientation isn't restored if t... | The correct message is WM_SIZE, but Daemin's answer points to the wrong WM_SIZE help topic. Check the wParam. Be careful as your window may be maximized but hidden.
|
290,436 | 318,750 | Macro Replacement during Code Generation | Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining... | You must tokenize your input before starting this kind of process. (I can't recommend the famous Dragon Book highly enough - even the ancient edition stood the test of time, the updated 2006 version looks great). Compiling is the sort of job that's best split up into smaller phases: if your first phase performs lexical... |
290,484 | 290,516 | Simple text menu in C++ | I am writing a silly little app in C++ to test one of my libraries. I would like the app to display a list of commands to the user, allow the user to type a command, and then execute the action associated with that command. Sounds simple enough.
In C# I would end up writing a list/map of commands like so:
class Men... | A very common technique is to use function pointers, or boost::function, indexed by the item name, or by having a vector of them and indexing by the item index for this job. Simple example using the item name:
void exit_me(); /* exits the program */
void help(); /* displays help */
std::map< std::string, boost::functi... |
290,488 | 290,521 | Does this code remove a file extension? | This isn't my code; I am trying to figure out what exactly this does. This is a part of a big, ancient system written in C (actually it was written 4 years ago, but most likely written by a late 80s programmer mentality). Part of the code:
char DestFile[256];
char DestFile2[256];
//This part is just to show an example... | You are correct.
In C a string is an array of chars terminated by a character with ASCII code 0.
So, first, DestFile is copied to DestFile2
Then a scan from the right is performed, to find the right-most occurrence of '.'
This returns a pointer to the char that matches, or null if no occurrence is found.
So now you hav... |
290,632 | 290,658 | How to overload operator<< that doesn't take or return ostream | Original Question
I am writting a logging class where the goal is to be able to do this:
// thread one
Logger() << "Some string" << std::ios::hex << 45;
// thread two
Logger() << L"Some wide string" << std::endl;
Currently my Logger header looks something like this:
#pragma once;
#include <ostream>
class Logger
{
... | You can use friend definition, which will define the operator in the surrounding namespace of the class, and make it only visible to operator overloading resolution (not callable manually using the ::operator<<... syntax):
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
template ... |
290,913 | 290,921 | C++: Derived + Base class implement a single interface? | In C++, is it possible to have a base plus derived class implement a single interface?
For example:
class Interface
{
public:
virtual void BaseFunction() = 0;
virtual void DerivedFunction() = 0;
};
class Base
{
public:
virtual void BaseFunction(){}
};
class Derived : public Base, publi... | C++ doesn't notice the function inherited from Base already implements BaseFunction: The function has to be implemented explicitly in a class derived from Interface. Change it this way:
class Interface
{
public:
virtual void BaseFunction() = 0;
virtual void DerivedFunction() = 0;
};
class Base : pu... |
290,952 | 291,001 | How to know (in GCC) when given macro/preprocessor symbol gets declared? | Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from.
Is it possible? If not, are there any partial solutions that may help?
F... | Use -E :
# shows preprocessed source with cpp internals removed
g++ -E -P file.cc
# shows preprocessed source kept with macros and include directives
g++ -E -dD -dI -P file.cc
The internals above are line-markers for gcc which are kinda confusing when you read the output. -P strips them
-E Stop after the preproce... |
291,065 | 291,261 | Saving extra data in a dll, how did they do it? | let me tell you a bit about where this question came from. I have been playing around with the SDK of Serious Sam 2, a first person shooter which runs on the Serious Engine 2. This engine introduces something called MetaData. MetaData is used in the engine to serialize classes and be able to edit them in the editor env... | This looks somewhat similar to Qt's moc (meta object compiler). In Qt's case, it generates extra C++ source files which are then compiled and linked together with the original source files.
A possible implementation in your example would be for the generated files to implement a set of functions which can be called to ... |
291,559 | 291,660 | Using mixed DLLs from /clr:pure projects | I'm building a project along with a Dll.
The Dll must support native code so I declared it as a /clr.
My project was initialy also a /clr project and everything was fine. However I'd like to include some NUnit testing so I had to switch my main project from /clr to /clr:pure.
Everything still compiles but any Dll call ... | Ok everything is working now
In fact, it has been working from the beginning.
Moral : don't try to cast a char* into a std::string
Weird thing : its ok in /clr until you return from the function. It crashes right away in /clr:pure
|
291,745 | 291,776 | Interview question about debugging, multithreading | I had telephone interview question yesterday.
The interviewer asked me if I had faced any challenging debugging issue?
I told him I once faced a problem debugging someone else's code and it took me 3-4 days to solve that. I used Windbg, symbols and a crash dump to solve the problem.
Now is this enough to tell? What is... | The general rule for interviews is to use the STAR model (my co-op coordinator is going to be proud here...):
S - Describe the situation you were in
T - Explain the task, providing enough info so that the interviewer understands the problem.
A - Describe the action you took to solve the problem.
R - What were the resul... |
291,792 | 291,949 | win32 select all on edit ctrl (textbox) | I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit Select All it doesn't select all. I can right click and click Select All but CTRL + A doesn't do anything. Why?
wnd = CreateWindow("EDIT", 0,
WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL |... | I tend to use MFC (forgive me) instead of Win32 so I cannot answer this definitively, but I noticed this comment added to a page on an MS site concerning talking with an Edit control (a simple editor within the Edit control):
The edit control uses WM_CHAR for
accepting characters, not WM_KEYDOWN
etc. You must Translat... |
291,871 | 292,438 | How to set a timeout on blocking sockets in boost asio? | Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?
I.e. I want to set a timeout on blocking socket in boost asio?
socket.read_some(boost::asio::buffer(pData, maxSize), error_);
Example: I want to read some from the socket, but I want to throw an error if ... | Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via setsocktopt(). I don't know if boost::asio provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable.
For... |
291,938 | 291,964 | why is this legal, c++ typedef func | i did this in msvc 2005.
typedef void (*cleanup_t)();
void func(cleanup_t clean)
{
cleanup_t();
}
Why does this compile? and not give me a warning? ok, it gave me a unreferenced formal parameter warning but originally i did this when clean was in a class no there was no unreferenced formal parameter when this cod... | It's executing a default initializer for the cleanup_t type to create a temporary of that type, and then never actually using that temporary.
It's a lot like a constructor call, the "MyClass()" part of "MyClass c = MyClass();", except that pointer-to-function types don't actually have constructors. Of course in my cod... |
292,109 | 1,735,543 | Outputting to stderr whenever malloc/free is called | With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log al... | malloc_hook(3) allows you to globally interpose your own malloc function. (There's __realloc_hook __free_hook etc. as well, I've just left them out for simplicity.)
#include <stdio.h>
#include <malloc.h>
static void *(*old_malloc_hook)(size_t, const void *);
static void *new_malloc_hook(size_t size, const void *call... |
292,124 | 292,151 | Is there any reason not to make a member function virtual? | Is there any real reason not to make a member function virtual in C++? Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.
On the other hand, I've been bitten a couple of times with forgetting to make a function vi... | One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default." Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual. Seems to me this would ha... |
292,450 | 292,582 | Wrapping Visual C++ in C# | I need to do some process injection using C++ but I would prefer to use C# for everything other than the low level stuff. I have heard about "function wrapping" and "marshaling" and have done quite a bit of google searching and have found bits of information here and there but I am still really lacking.
Things I have ... | I think P/Invoke is really the most straightforward approach:
Create a DLL in unmanaged C++, containing all the functionality you need to do the injection.
In your C# code, declare some static extern methods, and use the DllImport attribute to point them to your C++ dll. For more details, see the link provided by arul... |
292,740 | 292,764 | C++ reading from a file blocks any further writing. Why? | I am implementing a very simple file database. I have 2 basic operations:
void Insert(const std::string & i_record)
{
//create or append to the file
m_fileStream.open(m_fileName.c_str(), std::ios::out | std::ios::app);
if (m_fileStream.is_open())
{
m_fileStream << i_record << "\n";
}
m... | Change
while (!m_fileStream.eof())
{
getline (m_fileStream, line);
results.push_back(line);
}
to
while (getline (m_fileStream, line))
{
results.push_back(line);
}
Otherwise you will get one additional empty line at the end. eof() will return true only once you tried ... |
292,997 | 390,279 | can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio? | can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?
If so how?
Note I know you can use timers instead, but I'd like to know about these socket options in particular.
| Absolutely! Boost ASIO allows you to access the native/underlying data, which in this case is the SOCKET itself. So, let's say you have:
boost::asio::ip::tcp::socket my_socket;
And let's say you've already called open or bind or some member function that actually makes my_socket usable. Then, to get the underlying ... |
293,421 | 293,445 | C++: Using operator of two intrinsic types as a function object | I have a vector-like class that contains an array of objects of type "T", and I want to implement 4 arithmetic operators, which will apply the operation on each item:
// Constructors and other functions are omitted for brevity.
template<class T, unsigned int D>
class Vector {
public:
// Add a value to each item: n... | First, you should really return a reference from your operator+=, since you can later use them to implement operator+, operator- and so on. I will change that accordingly.
Also, your do_for_each has to be a template, since it has to know the precise type of the function object, as binary function objects are not polymo... |
293,499 | 293,563 | What happens if you don't return a value in C++? | Yesterday, I found myself writing code like this:
SomeStruct getSomeStruct()
{
SomeStruct input;
cin >> input.x;
cin >> input.y;
}
Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that was returned by this function got initialized to zero (when com... |
Did another SomeStruct get created and initialized somewhere implicitly?
Think about how the struct is returned. If both x and y are 32 bits, it is too big to fit in a register on a 32-bit architecture, and the same applies to 64-bit values on a 64-bit architecture (@Denton Gentry's answer mentions how simpler values... |
293,672 | 293,709 | Reading files larger than 4GB using c++ stl | A few weeks back I was using std::ifstream to read in some files and it was failing immediately on open because the file was larger than 4GB. At the time I couldnt find a decent answer as to why it was limited to 32 bit files sizes, so I wrote my own using native OS API.
So, my question then: Is there a way to handle f... | Apparently it depends on how off_t is implemented by the library.
#include <streambuf>
__int64_t temp=std::numeric_limits<std::streamsize>::max();
gives you what the current max is.
STLport supports larger files.
|
293,723 | 293,732 | How could I create a custom windows message? | Our project is running on Windows CE 6.0 and is written in C++ . We have some problems with the code , and we are unable to debug . We also found out that if in our application we create threads and try to printf from them , the output won't appear . The only output that will appear is the one from the main thread . I ... | It's certainly possible to do what you describe. You don't need to actually do anything to create a custom message for communication within your application: just make sure that the code that sends the message and the code that receives the message agree on what the message number actually is, and use a message number ... |
293,774 | 293,781 | How to create a QWidget with a HWND as parent? | With wxWidgets I use the following code:
HWND main_window = ...
...
wxWindow *w = new wxWindow();
wxWindow *window = w->CreateWindowFromHWND(0, (WXHWND) main_window);
How do I do the same thing in Qt? The HWND is the handle of the window I want as the parent window for the new QtWidget.
| Use the create method of QWidget.
HWND main_window = ...
...
QWidget *w = new QWidget();
w->create((WinId)main_window);
|
293,799 | 293,971 | How do I use std::tr1::mem_fun in Visual Studio 2008 SP1? | The VS2008 SP1 documentation talks about std::tr1::mem_fun.
So why, when I try and use std::tr1::mem_fun, why do I get this compile error?:
'mem_fun' : is not a member of 'std::tr1'
At the same time, I can use std::tr1::function without problems.
Here is the sample code I am trying to compile, which is supposed to cal... | Change it to this:
std::tr1::function<void (int)> f =
std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1);
f(2);
The binder requires the int argument. So you have to give it a placeholder which stands for the integer argument that the generated function object needs.
Btw: I'm not sure ... |
293,857 | 293,868 | Why does this const member function allow a member variable to be modified? | class String
{
private:
char* rep;
public:
String (const char*);
void toUpper() const;
};
String :: String (const char* s)
{
rep = new char [strlen(s)+1];
strcpy (rep, s);
}
void String :: toUpper () const
{
for (int i = 0; rep [i]; i++)
rep[i] = toupper(rep[i]);
}
... | A const member function, is a member function that does not mutate its member variables.
const on a member function does not imply const char *. Which would mean that you can't change the data in the address the pointer holds.
Your example does not mutate the member variables themselves.
A const on a member function... |
293,988 | 293,996 | Generic vector of vectors in C++ | Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?
Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. A... | You want to have template-typedefs. That is not yet supported in the current C++. A workaround is to do
template<typename T>
struct vecvec {
typedef std::vector< std::vector<T> > type;
};
int main() {
vecvec<int>::type intSequences;
vecvec<std::string>::type stringSequences;
}
In the next C++ (called c++... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.