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 |
|---|---|---|---|---|
3,079,411 | 3,079,491 | Creating a custom context menu Window (WinAPI) | I'm wondering how to create windows like these alt text http://img824.imageshack.us/img824/997/this.jpg
I'm refering to the one that says Marquee selection tool... these ones. I'm also not referring to the skin. I know how to do my own drawing and what not, this is not the issue. It's because windows usually need a par... | I think you are confusing the concept of owner windows and parent windows. Only dialog controls have parent windows, and these are automatically clipped by the parent's client area. Other windows have owner windows. This is a weaker relationship. There's nothing stopping a window from overlapping its owner.
Also, I... |
3,079,525 | 3,079,541 | RegOpenKeyEx return ERROR_SUCCESS but it shouldn't (windows 7) | I've got a problem about RegOpenKeyEx, the code:
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib, "Advapi32.lib")
int main () {
TCHAR *keyName = _T("SOFTWARE\\foobar2000\\capabilities");
HKEY key = NULL;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_ALL_ACCESS, &key... | Sounds like you're running into virtualization. IF the app has no manifest, when you try to write to HKLM\Software it actually writes to HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software. To prevent this, you can run the app elevated. You might want to add a manifest forcing it to run elevated every time. Alt... |
3,079,619 | 3,083,500 | Dialog of my Word add-in not using visual styles | I have written a Word add-in in C++ using plain Win32 API. It opens some dialogs but these are always shown without commctl6 visual styles on Vista+. The manifest is in place as RT_MANIFEST and resource ID - 2 (as shown below). When I invoke the same functionality/dialogs from my own test app, visual styles are OK.
Any... | Are you using ISOLATION_AWARE_ENABLED?
|
3,079,704 | 3,081,290 | Is it possible to map an address to the result of a function? | I'm writing a NES emulator in C/C++ for Mac OS (I've already written one, so I know the basics). Since many hardware registers are mapped to memory locations, I was wondering if there was some syscall I could use to map an address to the result of a function: when it would be accessed, the function would be called. (I'... | Maybe you could try installing a SEGV handler and checking the faulting address there. As I don't use Mac OS I can't help you more.
|
3,079,742 | 4,063,550 | boost::asio handshake through http proxy? | Quite new to boost and asio, need help:
connect to proxy
asio::ip::tcp::socket socket_;
send CONNECT host: ssl server to the proxy
receive response 200
asio::ssl::context ctx(io_service, asio::ssl::context::sslv23);
sslsocket_(socket_,context)
try handshake
sslsocket_.async_handshake(asio::ssl::stream_base::client, ... | Forgot to mention that was running the application in VMplayer with NAT network; bridged removed the problem with initial handshake but sometimes after reconnect saw the same message;
using the method in Sam's link got to "unexpected record" during handshake - google said on this error about renegotiations but that was... |
3,079,836 | 3,079,848 | c++ static won't link | Can you help?
The following code:
class MT
{
public:
static int ms_number;
};
int MT::ms_number;
yields:
Error 8 error LNK2005: "public: static int MT::ms_number"
(?ms_number@MT@@2HA) already defined in ProjName.obj
Why?
| You need to move this line:
int MT::ms_number;
out of your .h file and into a single .cpp file.
|
3,079,978 | 4,002,502 | Making Vista / 7 User Frame control? (WinAPI) | I notice Vista/7 uses this type of control as well as Windows Live Messenger. This is the control:
How can this control be programably added to a WinAPI application?
Thanks
| This resource is Bitmap 7016 in explorer.exe's resources. It is a 32 bit bitmap, so it has an extra alpha channel. This is how it is done.
|
3,079,980 | 3,080,108 | Calling a function from a derived template class | My base class:
//Element.h
class Element
{
public:
Element();
virtual ~Element(){}; // not sure if I need this
virtual Element& plus(const Element&);
virtual Element& minus(const Element&);
};
Derived template class:
//Vector.h
#include "Element.h"
template <class T>
class Vector: public Element {
T x, y, z;
public... | I think the compiler/linker means it when it tells you Undefined symbols: "Element::plus(Element const&)" . These symbols (plus and minus for Element) have been declared but they have not been defined.
|
3,080,049 | 3,080,209 | Should i always use GL_ARGB format for all textures in OpenGL? | This has been bothering me a while... and it's really hard to really see any difference in performance, so i ask here:
If my images doesnt use alpha channel, should i use 'GL_RGB' for saving them in GFX card memory, or 'GL_ARGB' as if that would be faster in processing since its full 32 bit block?
Or does GFX cards aut... | Choose the formats appropriate for your texture data, and let the video card driver worry about the details. Don't try to outsmart it. OpenGL implementations are quite well-optimized and will make all of the necessary decisions for you for the best performance, whether that means converting all textures to 32bpp or som... |
3,080,137 | 3,080,155 | What is wrong with this code? | int main()
{
char *name = new char[7];
name = "Dolphin";
cout << "Your name is : " << name <<endl;
delete [] name;
}
Why doesn't the VC++ compiler complain?
| You've got two questions here:
First, What's wrong with code? Well ...
When you assign "Dolphin" to name you are not copying into the allocated array you are adjusting the pointer to point to a string literal. Later you try to delete what the pointer points to. I'd expect this to crash horribly in some environments.
If... |
3,080,156 | 3,080,176 | How do I link in functions from a .cpp source file that also has a 'main'? | I want to use some functions from a .cpp source file that has a main function in my .cpp source file. (I'm building with make and gcc.)
Here's the rule from my Makefile:
$(CXX) $(CXXFLAGS) $(INCLUDES) $(SRCS) $(LIBS) -o $@
And here's the output (with some names changed to prevent distraction):
$ make foo
g++ -g -Wall... | what you could do is wrap each main() function in an #ifdef block, then use the command line to define the symbol which will cause the relevant main to be used.
#ifdef USE_MAIN1
int main(void)
{
}
#endif
Then ensure the gcc command line gets something like this added to it
-DUSE_MAIN1
Or just restructure your code!
|
3,080,191 | 3,080,258 | Window Style for shading? | When a menu item or context menu is made, it has a shadow, if I create a window with WS_POPUP instead of WS_CHILD it has no shadow. How can I get the shadow? Thanks
| It is enabled with WNDCLASSEX.style. Turn on the CS_DROPSHADOW style. I think this only works on top-level windows.
|
3,080,224 | 3,080,246 | Ways to parse XML in C++ (Win32) | I'm looking for a way to parse XML in C++ in Windows and I've found a few such as MSXML, Xerces, TinyXml etc but I'm wondering which is best in terms of performance and features. My requirements are that it must be able to be static linked or have the source included in the project itself and must not require any addit... | I used libxml with success. The API is a bit confusing and complicated, but once you get it it works pretty good. Besides it is stuffed with functionality, so if you need that, go with libxml.
You dont have to worry about bloated binaries since you can only link the parts you need. You dont need to include the complete... |
3,080,298 | 3,080,324 | Nesting of Structs and Classes | #include<iostream>
using namespace std;
struct My_Class{
class My_struct{
int am_i_in_class_or_struct;
};
};
int main(){
cout<<sizeof(My_Class)<<endl;
cout<<sizeof(My_struct)<<endl;
cout<<sizeof(int);
}
Please Explain:
when i executed the above program on Turbo C i got output:
1
2
2
Now shouldn't the size be same i... | You are nesting the declarations, but not the data. Declaring one class inside another class does not magically make the data members of the inner class also members of the outer class. Your code is virtually equivalent to a mere
struct My_Class{
};
class My_struct{
int am_i_in_class_or_struct;
};
with only one dif... |
3,080,377 | 3,080,917 | How do I use DrawPrimitiveUP so it uses the color value from my defined struct? | I need to draw lines using DrawPrimitiveUP and I need it to use the color value from my defined structure.
Important snippets from the code:
struct PointVertexColor
{
float x, y, z; // Position
DWORD color; //Colour
};
#define D3DFVF_PointVertexColor ( D3DFVF_XYZ | D3DFVF_DIFFUSE )
PointVertexColor myLines[102... | The problem was obvious if you know it - you can't use vertex color and lighting at the same time. The solution is to disable lighting for that part of the code and then re-enable it later.
Hope it helps someone with the same question.
|
3,080,439 | 3,080,448 | C++ reference variable across files | I have a project where I need to reference a variable declared in one CPP file in another, is that possible?
If so, how?
| It is possible, if you declare it as global (top-level, above any function definition) and use "extern ;" in other files to make it known to the compiler.
// Main.cpp
#include <...>
int myNum;
int main(int argc, char** argv)
{
// MAGIC BE HERE
return 0;
}
and
// Second.cpp
#include <...>
extern int myNum;
i... |
3,080,560 | 3,080,649 | C++ TLS, somethings wrong | I'm learning about Thread Local Storage... (TLS)
Here is my TLS Alloc code:
//global variable
DWORD g_dwTlsIndex;
//inside DLLMain:
int val= 5;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_dwTlsIndex = TlsAlloc();
if ((g_dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES)
{
printf("No more indexes... | A few notes:
Your error checking statement should read:
if (g_dwTLSIndex == TLS_OUT_OF_INDEXES).
As it stands, you're assigning g_dwTlsIndex twice (and thus losing the reference with the first assignment.)
Do some basic debugging:
Call TlsGetValue in the line immiediately after TlsSetValue. Does that work at least?
... |
3,080,579 | 3,087,910 | Ampersand accelerators cause a beep in a Win32 dialog | I have a dynamically created toolbar on a plain Win32 dialog. My buttons are added with & shortcuts which correctly puts underscore to characters following ampersand but pressing Alt+(char) causes a beep and the button is not clicked.
It has been a while since I have done Win32 API development. Is there something that ... | Well... You have to write code to handle these keypresses and convert them into WM_COMMAND messages. The traditional way to do this is to define an accelerator table and process them using TranslateAccelerator() - but of course, you're free to do it however you like... Just make sure the keys you handle jibe with the k... |
3,080,632 | 3,506,819 | NetBeans6.9 C++ runtime error | In NetBeans 6.9 in windows version I use CygWin for C++ programming.I can compile my simple program and BUILD SUCCESSFUL message show by output window in NetBeans but when run my project this message show in external terminal :
/cygdrive/c/Users/SjB/Documents/NetBeansProjects/CppApplication_3/dist/Debug/Cyg
win-Windows... | You should add the environment variable to your path.
Go to Control Panel -> Systems-> Advanced -> Environment variables and edit the $PATH variable by adding C:\cygwin\bin
Then, reload your project in NetBeans and it should work.
|
3,080,764 | 3,081,038 | 'this' pointer in macro and function | I have some code which use 'this' pointer of class which calls this code. For example:
Some::staticFunction<templateType>(bind(FuncPointer, this, _1));
Here is I'm calling bind function from boost. But it doesn't matter. Now I have to wrap this code. I made a macro:
#define DO(Type, Func) Some::staticFunction<Type>(bi... | The this keyword can be put by the function you call
class MyClass {
// ...
template<typename Type, typename Func>
void doit(Func f) {
Some::staticFunction<Type>(bind(f, this, _1));
}
};
After which you can call
doit<templateType>(FuncPointer);
If you like you can inherit the function
// T must be a deri... |
3,081,033 | 3,081,145 | Number of arguments in macro definition | I have some templated function which has different number of arguments due to the template-type. This function is wrapped with macro definition.
#define SomeTemplate(TemplateType, Arguments) someFunc<TemplateType>(Arguments);
Everything is okay when I'm using only one argument for function calling, but I need in more.... | the only way to do that us using __VA__ARGS__ in the macro definations, however, its not as portable, beacuse older compilers like VC6 doesn't support var arg'ed macros, see:
MSVC
GCC
|
3,081,052 | 3,081,072 | Correct data structure to use for (this specific) expiring cache? | I need to read from a dataset which is very large, highly interlinked, the data is fairly localized, and reads are fairly expensive. Specifically:
The data sets are 2gigs - 30gigs in size, so I have to map sections of the file into memory to read. This is very expensive compared to the rest of the work I do in the a... | Seems like you are looking for an LRU (Least Recently Used) cache: LRU cache design
|
3,081,108 | 3,081,168 | Custom iterator: how do I keep track of it? | I have this situation:
I have a class which keeps track of an array of pointers. I built a custom iterator which loops through this array.
My problem is on how to make it threadsafe, especially while incrementing/decrementing?
Here is a draft of the relevant parts of what I have:
typedef fruit * iterator;
class fruits... | The standard containers maintain their iteration state in iterator objects separately from the container, so there can be multiple iterations over the container at the same time. So begin() and end() return iterators, but don't change the state of the container; operator++ acts on iterators, not the container. For a si... |
3,081,246 | 3,081,269 | Why aren't (C++) virtual destructors enforced for a base class | Destructors aren't virtual by default to not hurt when its not needed, which is fine.
But in case of a base class derived class scenario, is there any use case for not having a virtual destructor? If not could it be possible (does it make sense) for the compiler to complain if a class derives from a base class which ha... | The problem with your idea is that it's conceivable that someone is using a non-virtual base class destructor as an optimization (if you're never going to destroy via a base-class pointer, then the missing virtual won't hurt you, and still avoids the vtable entry).
Since it COULD be used, it's allowed. I'd think an opt... |
3,081,289 | 3,081,405 | How to read a line from a text file in c/c++? | After exhaustive googling and visiting many forums, I am yet to find a good comprehensive answer for this question. A lot of the forums suggest using the get line
istream& getline (char* s, streamsize n ) function. My question is what if I don't know what the length of each line is and cannot predict what the size may... | In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.
If there's a chance you may have really really long lines and you have to process line by line, you could malloc a re... |
3,081,305 | 3,081,334 | What is the difference between r-value references and l-value references? (CodeGen) | What does an r-value reference look like from a lower-level perspective. I just can't seem to wrap my head around it! Can I see an example of generated code (either equivalent C or x86/x64) from a r-value reference vs. a l-value reference?
For example, what would this construct look like? Let's assume no copy elision f... | There is no difference for the purposes of code generation. The only semantic difference between the two is that you know an RValue reference is about to be destroyed, while an lvalue reference will not.
|
3,081,340 | 3,082,115 | QTableView sorting signal? | I use QTableView + QStandardItemModel to show some data (data stored in some other data structure), and this table view is sortable.
Since it is sortable, when sorting this model, I also need to sort the order of stored data. I try to implement a slot for the sorting signal, but I don't know what signal is emitted when... | The Header of the View can be obtained by
QHeaderView * QTableView::horizontalHeader () const
Now with the obtained QHeaderView, you can connect a slot to the signal,
void QHeaderView::sectionClicked ( int logicalIndex ) [signal].
From the Qt 4.5 documentation, This signal is emitted when a section is clicked. The... |
3,081,446 | 3,085,256 | Drawing list of points in SDL? | If i have an array of coordinates for a path(Such as in a paint program), what is the best way to render the entire path with SDL?
I looked at setting pixels individually, but from what i've seen that's a bad idea.
I also thought about drawing all the coordinates as SDL_Rect's, but rendering a large list of rect's eac... | You can implement yourself the Bresenham line algorithm directly accessing the framebuffer but I think you'll be doing much better using OpenGL...
|
3,081,505 | 3,081,553 | Is there an equivalent of str_replace in C++? | In PHP, there is a str_replace function that basically does a find and replace. Is there an equivalent of this function in C++?
| Not exactly, but take a look at the Boost String Algorithms Library - in this case the replace functions:
std::string str("aabbaadd");
boost::algorithm::replace_all(str, "aa", "xx");
str now contains "xxbbxxdd".
|
3,081,537 | 3,081,651 | How can I make a variable of the same type as another using templates? | I'd like to create a variable which matches the type of another variable by way of a template such that if the other variable ever changes type to match, the one derived from it via a template also changes its type.
How can I do this with templates in C++?
The purpose is to ensure that when I read from disk into a temp... | If you don't have decltype available in your compiler, you can write a template function to accomplish this. It's kind of ugly but it will get the job done.
template<typename T>
T read_alike(int fd, T const &unusedVar)
{
T realVar;
if (::read(fd, &realVar, sizeof(realVar)) != sizeof(realVar)
throw std:... |
3,081,539 | 3,081,558 | Why is my operator<< overloading not working? | Error:
..\Record.cpp: In function `std::ostream& operator<<(std::ostream&, Record&)':
..\Record.cpp:83: error: no match for 'operator<<' in 'out << Record::date()()'
Record.cpp:
/*
* Record.cpp
*
* Created on: Jun 13, 2010
* Author: DJ
*/
#include <iostream>
#include "Record.h"
using std::string;
using st... | Your operator<< should take const references (const Date &).
If your operators take non-const references, they won't work with temporary objects (such as the one returned from Record::date). This is what's causing the error.
Note that changing to const references means you will need to change any member functions calle... |
3,081,669 | 3,081,693 | How to call a C++ function pointer from C? | I was successfully to finally be able to use TUI header from PDcurses library in my C++ project in a previous post here.
now in my class I am including the C header:
#include "tui.h"
tui is in C and has this definition for menu:
typedef struct
{
char *name; /* item label */
FUNC func; /* (pointer to) functio... | C++ class objects have a "this" pointer, which is sort of invisibly passed as the first argument to a class member function. That means you can't use a non-static member function for a C-style function pointer that takes 0 arguments.
So solve this, you have a few choices. I'd need more detail before telling you which... |
3,081,697 | 3,081,714 | Should you format operator<< for classes? | As in, should the operator>> match the operator<< ?
Database Example:
If the operator>> reads in something of the following format:
2
Joe 500 20 1
Bob 250 30 0
should the operator<< output that? Or something like this:
Record: 1/2
Name: Joe
Balance: 500
Transactions: 20
Premium Account: Yes
And then have a separate w... | If you have an istream operator>> overload for a type that reads data in a particular format, then if you implement an ostream operator<< overload for the same type, it should output in the same format (otherwise, it could get quite confusing).
|
3,081,717 | 3,086,104 | 24 Bit Toolbar Button Images? (WinAPI) | I'm using pure win32. How can I use 24 bit images instead of 8 bit?
Thanks
| You can set the imagelist for the toolbar with the TB_SETIMAGELIST message.
|
3,081,765 | 3,081,805 | Problem with using getline and strtok together in a program | In the below program , I intend to read each line in a file into a string , break down the string and display the individual words.The problem I am facing is , the program now outputs only the first line in the file. I do not understand why this is happening ?
#include<iostream>
#include<string>
#include<fstream>
#incl... | I'm new to C++, but I think an alternative approach could be:
while(getline(InputFile, store))
{
stringstream line(store); // include <sstream>
string token;
while (line >> token)
{
cout << "Token: " << token << endl;
}
}
This will parse your file line-by-line and tokenise each lin... |
3,081,815 | 3,081,883 | C++ errors while compiling | I am trying to compile a game, but getting 100+ errors like:
C:\Users\AppData\Local\Temp\cctQCagR.o: In function `load_image(std::string)':
main.cpp:(.text+0x4bd4): undefined reference to `std::string::c_str() const'
C:\Users\Bill\AppData\Local\Temp\cctQCagR.o: In function `createShip(float, float)':
main.cpp:(.text+0x... | I believe you're trying to compile main.cpp with gcc instead of g++.
#include <string>
#include <stdio.h>
int main()
{
std::string bla;
bla = "BLA BLA";
printf("%s\n",bla.c_str());
return 0;
}
If you build the above code snippet with gcc you get the errors you mention.
If you use g++ it build ok, this ... |
3,081,924 | 3,082,019 | Finding the smallest window | Given two arrays A[n] and B[m], how can I find the smallest window in A that contains all the elements of B.
I am trying to solve this problem in O(n) time but I am having problem doing it. Is there any well know algorithm or procedure for solving it.
| countLet's call window 'minimal' if it can't be reduced. I.e., after increasing its left border or decreasing its right border it's no longer valid window (doesn't contain all elements from B). There three in your example: [0, 2], [2, 6], [6, 7]
Let's assume say that you already found leftmost minimal window [left, rig... |
3,081,965 | 3,082,008 | using C# DLL from C++: problem with functions with strings as parameters | Starting from this example: http://support.microsoft.com/kb/828736 I have tried to add a test function in my C# DLL which takes strings as parameters. My C# DLL code is as follows:
namespace CSharpEmailSender
{
// Interface declaration.
public interface ICalculator
{
int Add(int Number1, int Number2);
... | Without trying to compile this, perhaps the interop expects the string to be of BSTR type. Can you try the following?
pICalc->StringTest(CComBSTR(L"hello"), CComBSTR(L"world"), &lResult2);
OR
pICalc->StringTest(::SysAllocString(L"hello"), ::SysAllocString(L"world"), &lResult2);
|
3,082,045 | 3,084,252 | How to use for_each with the function as the overloaded operator() | I have a std::vector of function objects. Each object can take an int, so I can say obj(4) and get an int result. How can I use the algorithm for_each to work on each element of the vector?
| You would have to create a functor 'calling' each object:
struct Caller {
int value;
void operator()( const YourFunctorHere& f ) const {
f( value );
}
} caller;
std::for_each( functors.begin(), functors.end(), caller );
|
3,082,113 | 3,082,186 | calculating factorial using template meta-programming | I do not understand how this piece of code (from Wikipedia) works:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::val... |
What is this weird template that takes <int N>?
In C++, template arguments can either be types (prefixed with class or typename) or integers (prefixed with int or unsigned int). Here we are in the second case.
What is this second weird template <>?
template<> struct Factorial<0> is a complete specialization of ... |
3,082,291 | 3,082,442 | Virtual function calling using dereference object | I have a base class pointer pointing to a derived class object. I am calling foo() function by using two different ways in the code below. Why does Derived::foo() get called in the first case? Shouldn't (*obj).foo() call Base::foo() function as it has already been dereferenced?
class Base
{
public:
... |
// SCENARIO 1
(*obj).foo();
Note that
obj is a misnomer here, since it doesn't refer to an object, but to a pointer,
(*ptr).foo() is just a roundabout way to do ptr->foo().
*ptr doesn't result in an object, but in a reference Base& to the object. And a virtual function call through a reference is subject to dyn... |
3,082,397 | 3,082,459 | IsDirty name for member function of CField class | What was the raionale behind having a function by the name IsDirty() in CField Class in MFC.
| The terms "clean" and "dirty" are quite commonly used in data processing. When you receive a copy of some data structure from a persistent storage like a data base or file system, it is said to be "clean", unmodified, not touched. Once you are done with the data, the backing storage does not need to be updated for clea... |
3,082,700 | 3,084,434 | Is there a way to 'expand' the #define directive? | I have a lot of "stupid" #define in a project and I want to remove them. Unfortunately, I can't do a simple search and replace, since the #define is parameterized. For example:
#define FHEADGRP( x ) bool _process_grp##x( grp_id_t , unsigned char )
This is used to generate headers of a couple of functions. I would like... | Yes, there is - since you're using Visual Studio.
The Visual Studio IDE has a powerful search & replace mechanism. You seem to assume it can only handle literal strings. It can do more. Hit Ctrl-Shift-H for a global search and replace. In the "Find options", select "Use: Wildcards".
Now replace FHEADGRP(*) by bool _pro... |
3,082,751 | 3,082,759 | when returning by address, doesnt this go out of scope? ( SDL) | this is a code example from lazyfoo's SDL tutorials.
SDL_Surface *load_image( std::string filename ) {
//Temporary storage for the image that's loaded
SDL_Surface* loadedImage = NULL;
//The optimized image that will be used
SDL_Surface* optimizedImage = NULL;
//Load the image
loadedImage = SDL_LoadBMP( filename... | It does, but not the allocated memory pointed by it. It is a merely 4 byte pointer variable, the only thing needed from it is to retain its value.
The value is the address. The address is something allocated in manually controlled fashion, and deallocating it requires calling functions the compiler does not know about.... |
3,082,800 | 3,082,810 | Only implement copy constructor, no assignment constructor | When the class with a member which is a pointer, we need implement a copy constructor for it. I have a question, if we have implemented a copy constructor, should we implement an assignment constructor too?
Best Regards,
| It is not called an assign constructor but rather an assignment operator, and yes you should. The rule of thumb is: if you need to write a destructor then you should also provide a copy constructor and assignment operator (or block the compiler from generating one)
|
3,082,900 | 3,082,917 | Preventing compilers from defining copy constructors and operator = overload for C++ Classes | Is there a way by which we can prevent compilers from defining copy constructors, operator = overload for C++ classes.
| You can declare these functions as private which prevents people from using them when working with your class and at the same time prevents the compiler from generating them.
|
3,082,950 | 3,083,011 | When are global static const variables being initialized? | I tried to search the site for this question but didn't find this exactly, although this subject is being discussed a lot...
I have this declaration in a cpp file, not within any function:
static const char* gText = "xxxxxxxxxxx";
Although it has a fixed size, I get a warning from a static analysis tool (Klocwork) whe... | It is a false positive. strlen is probably abstracted as returning an unknown positive number, so that when analyzing the pattern memcpy(dest,src,strlen(src)); the analyzer does not realize that the reading part of the copy is safe as soon as src is a well-formed string.
If you were using strcpy, the analyzer would pro... |
3,082,995 | 3,083,057 | Return-type polymorphism for pass-by-value | I'm not sure if the question title is accurate... Let me start by explaining my original simple scenario, and then move on to explain what would I like to do, but can't.
Originally, I had something like:
class Operand;
Operand genOperandA() { ...; return Operand(); }
Operand genOperandB() { ...; return Operand(); }
..... | There might be other designs that doesn't require you to use pointers, but if you need or want to go this way, this might interest you.
If returning a pointer is a problem (because of the need to "clean-up" things), you definitely should consider using smart pointers as return type.
Here is an example of your factory ... |
3,083,016 | 3,083,035 | int to string conversion | I would like to save files with different names in a loop. I use a library that needs a char as a parameter of the file...
for(int i=0;i<nodes;i++){
for(int j=0;j<nodes;j++){
char a[20]="test";
char c[20]="xout.dat";
Lib::SaveFile(_T(a), _T(c));
}}
The above code works, but I would like to change the name of t... | char name[30];
sprintf(name, "%d-%d-%s", i, j, c);
|
3,083,280 | 3,083,603 | A good repartition algorithm | I am implementing a memcached client library. I want it to support several servers and so I wish to add some load-balancing system.
Basically, you can do two operations on a server:
Store a value given its key.
Get a value given its key.
Let us say I have N servers (from 0 to N - 1), I'd like to have a repartition fu... | You're probably looking for something that implements consistent hashing. The easiest way to do this is to assign a random ID to each memcache server, and allocate each item to the memcache server which has the closest ID to the item's hash, by some metric.
A common choice for this - and the one taken by distributed sy... |
3,083,355 | 3,083,425 | Why and when is worth using pointer to pointer? |
Possible Duplicate:
How do pointer to pointers work in C?
Hello,
Altough I think I passed the newbie phase in programming I still have some questions that somehow I can't find them explained. Yes, there are plenty of "how to"s overthere but almost always nobody explains why and/or when one technique is useful.
In my... | Well, it is somehow hard to answer to such a general question.
First answer of a C++ programmer will certainly be : Do not use pointers in C++ ! As you have a lot of safer ways to handle problems than pointers, one of your goal will be to avoid them in the first place :)
So pointers to pointers are seldom used in C++. ... |
3,083,458 | 3,084,359 | Looking for any good(and free) cross-platform CLI parsing library for a command line utility | I am currently working on a CLI utility which I feel can be improved a lot by adding a framework.
Basically the utility revolves around lots of command line syntax AND parsing the output. Currently the code is scattered all around with lots of individual inhouse run() and readFromRunOutput() calls with hardcoded CLI ar... | I don't understand what exactly you are looking for, but have a look at Boost Program Options. It can handle most CL Parsing out of the box and is easily extendible for the rest.
|
3,083,532 | 3,083,763 | Dividing large integer by large integer | Guys I'm working on class called LINT (large int) for learning purposes, and everything went ok till know. I'm stuck on implementing operator/(const LINT&). The problem here is that in when I want to divide LINT by LINT I'm getting into recursive fnc invocation i.e:
//unfinished
LINT_rep LINT_rep::divide_(const LINT_r... | When doing your part (1) you can't divide; you have to repeatedly subtract, or guess to subtract a multiple, just like when you do it by hand. You can 'guess' more effectively by setting upper and lower bounds for the multiple required and doing a binary-chop through the range.
I've done a similar thing myself; it's a ... |
3,083,649 | 3,083,879 | best practice for implementing a Search-Function via prepared statements | I'm trying to implement a Search-Function using c++ and libpqxx.
But I've got the following problem:
The user is able to specify 4 different search patterns (each of them optional):
from date
till date
document type
document id
Each of them is optional. So if I want to use prepared statements I would need 2^4 = 16 di... | The best you can do is to have four different ->prepare clauses, depending on how many search criteria are actually used, concatenate the criteria into your String, and then branch to one of the four prepare code blocks. (That will probably spook your style checker into thinking you are creating an injection vulnerabil... |
3,083,758 | 3,123,425 | How do I diagnose problems in loading a gstreamer plugin? | I have created a gstreamer plugin with an element inside that would generate some data when put in a pipeline (by following the GStreamer Plugin Writer's Guide).
My problem is that I cannot load my plugin in a test application. When I call gst_element_factory_make("myextractor", NULL) the result is always NULL.
More da... | It might be because the loader can't find your plugin, you should check that your plugin is in the shared library path:
Make sure you've set the LD_LIBRARY_PATH environment variable to the directory containing your compiled plugin.
In cygwin, add this to your .profile, or run it before you run your program:
export LD_L... |
3,083,808 | 3,083,824 | strange catch clause... C++ | What is this catch clause??
STD_CATCH_ALL_with_kMETHODID(...)
Its used in a python interpreter extension...
| How about right-click and select Go To Declaration (using Visual Studio). You may try Go To Definition as well. If you cannot find it, it means you need to include a header where this macro is defined.
|
3,083,903 | 3,084,189 | PostThreadMessage to another process | I want to post a message to a thread that is running as another process (in particular as a windows service). I've read the documentation for PostThreadMessage but there are some things unclear for me.
How do I get a handle for my service's thread?
The system only does marshalling for system messages (those in the ran... | PostThreadMessage is less than ideal here. Getting the thread ID is indeed a problem since your service will have to run more than one thread. One to implement the service, another to pump a message loop that's required to read the messages. CreateToolHelp32Snapshot() can enumerate the threads but you will still not... |
3,083,932 | 3,084,015 | Modify in place the elements of a vector | The following doesn't work as desired (print 2) because, I guess, the nodes are passed by value even though the vector is passed by reference. How could I fix it?
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
class Node{
public:
int value;
Node(int);
... | When you execute the line nodes.push_back(n);, the vector is resized, invalidating previously held references as it copies the existing members to a newly allocated memory block. In your case, *this inside createChildren is such a reference (to asdf[0]). Changing value in it is no longer defined behavior because the de... |
3,083,956 | 3,083,962 | Simple question about #import | Is #import or #include a job that is handled by the complier or by the linker?
| Anything that starts with # is a preprocessor directive and is expanded by the preprocessor, which is a step that happens before compilation.
|
3,083,987 | 3,085,097 | calling class-specific operator new | The expression operator new(sizeof(T)) allocates T bytes via ::operator new, correct?
Is there any way to call the class-specific version of operator new if it exists, exactly the way how new T() allocates memory (before calling the constructor)?
T::operator new(sizeof(T)) gives a compile-time error if T does not defin... | The standard library solves this problem using an allocator object whose type is set as a template parameter of the class that needs a customizable allocation algorithm.
I don't think there's any complete way to do what you asked, as already evidenced by your second bullet. There's no way for the compiler to know which... |
3,084,109 | 3,084,418 | Caching the end iterator - Good idea or Bad Idea? | Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:
std::vector<int> vint;
const std::vector<int>::const_iterator end = vint.end();
std::vector<int>::iterator it = vint.begin();
while (it != end)
{
....
... | In the simple case of a vector, the end iterator will change when you add or remove elements from the container; though, it's usually safest to assume that if you mutate the container while iterating over it, all iterators to it become invalid. Iterators may be implemented differently in any given STL implementation.
W... |
3,084,689 | 3,084,788 | How to create Handler | Add next changes:
Emily::oSeMac^ Terminal;
Emily::AsyncSocketController^ _socketManager;
delegate void DataArrival(String^, array<unsigned char, 1>^, System::Net::IPEndPoint^);
void _socketManager_onDataArrival(String^ SocketID, array<unsigned char, 1>^ SocketData, System::Net::IPEndPoint^ RemoteIP)
{
... |
_socketManager->onDataArrival += gcnew DataArrival(this,
&Test::Form1::_socketManager_onDataArrival_);
DataArrival is delegate:
public delegate DataArrival(String^, array<unsigned char, 1>^, System::Net::IPEndPoint^);
Possibly it is already defined somewhere, with other name - look this delegate definition in E... |
3,084,917 | 3,084,956 | Access private variable in global scope | In this below code, the foo function in the global scope tries to access the private variables of a Box, which ofcourse doesn't work. I have to make the foo function work with one line of code at the place show code for a school assignment.
#include <iostream>
using namespace std;
class Box {
int x,y;
pu... | Declare foo as a friend function inside Box
#include<iostream>
class Box {
int x,y;
public:
Box(int xi,int yi) :x(xi),y(yi){}// Always use initializer list for initializing data members, i.e. prefer initialization over assignment
friend bool foo(Box,Box);// friend functions can acc... |
3,084,945 | 3,086,667 | Build a Cross Compiler | I'm trying to compile a c++ file and generate an asm or s file to be disassembled and run in PSIM. Whenever I try to do this I get errors. I am attempting to compile to mipsI-linux. I think I've determined that my cross compiler that was given to me is not working correctly for some reason. Can anyone give me some help... | You probably want to take a look at crosstool-NG (based on crosstool) which seems to make building a cross-compiler toolchain relatively easy.
|
3,085,070 | 3,085,141 | Finite State Machine parser | I would like to parse a self-designed file format with a FSM-like parser in C++ (this is a teach-myself-c++-the-hard-way-by-doing-something-big-and-difficult kind of project :)). I have a tokenized string with newlines signifying the end of a euh... line. See here for an input example. All the comments will and junk is... | If you have nesting scopes, then a Finite State Machine is not the right way to go, and you should look at a Context Free Grammar parser. An LL(1) parser can be written as a set of recursive funcitons, or an LALR(1) parser can be written using a parser generator such as Bison.
If you add a stack to an FSM, then you're ... |
3,085,257 | 3,085,600 | Why disable CObject's copy constructor and assignment | The MFC's root object CObject's copy constructor and assignment are disabled by default.
In MSDN, there is a description
The standard C++ default class copy
constructor does a member-by-member
copy. The presence of the private
CObject copy constructor guarantees a
compiler error message if the copy
constru... | The default copy constructor is member-by-member, not bitwise.
Most CObject-derived classes contain - and manage directly - some system resources, that have no reference counting or similar mechanism, so the choice was probably made with the default use case in mind.
e.g. CGDIObject is roughly:
class CGDIObject : publi... |
3,085,315 | 3,085,353 | memory footprint issue | I was just curious I have a binary executable file in unix around 9MB. is that considered a large memory footprint? the client will be calling this to generate some values and subsequently queue messages elsewhere. I am just curious who is one suppose to know how when is it too big a memory footprint for a program and ... | Everything is relative. It's large footprint if the app is running on a machine with 8MB of RAM. It's not large if the app is running on a machine with 64GB RAM. Then again, it might be large even on a 64GB RAM machine if most of the RAM has been gobbled up by some huge Oracle instance (for example).
You should also ta... |
3,085,349 | 3,085,368 | Function Should Return Value Question | Given a function like so
bool RequestStatus()
{
...
if (code == myCode) {
return true;
} else {
return false;
}
}
Why would the compiler complain that "Function should return value". Unless I am missing something, how else could it not return true or false? Is it because the value of ... | if you write return (code == myCode); you will save lines, make the compiler happy, and generally be writing in a more C++-ish style.
|
3,086,147 | 3,086,281 | error in one line Xerces program | The following application gives me an access violation on its first line, whats with that?
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <xercesc/util/XMLString.hpp>
using namespace xercesc;
int main()
{
XMLCh* path= XMLString::transcode("... | The obvious error in your program is that you are not initializing xerces-c before using it.
http://xerces.apache.org/xerces-c/program-2.html
You must call XMLPlatformUtils::Initialize() before making any other calls to xerces-c.
|
3,086,308 | 3,086,464 | function templates with class template typedef arguments | the following code is an example of something I'm trying to do in a large project:
#include <iostream>
#include <vector>
// standard template typedef workaround
template<typename T> struct myvar {typedef std::vector<T> Type;};
template<typename T>
T max(typename myvar<T>::Type& x)
// T max(std::vector<T>& x)
{
T y;... | Deducing the enclosing type (or any attributes of the enclosing type) from its the nested type is impossible. It is one of the examples of so called non-deduced context in C++.
While the template function declaration itself is legal, you won't be able to call your function as mere max(var) since the template argument ... |
3,086,408 | 3,086,433 | Search a std::string | I'm looking to search a string for example:
std::string str = "_Data_End__Begin_Data_End";
|_________| |_____________|
data data
section1 section2
If i'm searching for "Begin" in str i want to make sure that it does look in "data section2" if it wa... | std::string::find() has an optional argument to indicate where to begin searching:
str.find("Begin", length_of_data_section1);
|
3,086,656 | 3,086,992 | Help with WinAPI Toolbar | I'm trying to create a toolbar where my bitmaps will be 40x40 and I'm trying to make the toolbar 40 pixels in width. I want it to be a vertical toobar. I'm getting nothing but horizontal results from this code:
HWND OGLTOOLBAR::create(HWND parent,HINSTANCE hInst,WNDPROC prc, int *toolWidthPtr)
{
if (toolhWnd != NUL... | From the SDK docs:
Creating a Vertical Toolbar
The key to creating a vertical toolbar
is to include CCS_VERT in the window
style, and to set the TBSTATE_WRAP
style for each button
Emphasis added.
|
3,086,691 | 3,087,606 | C++ Partial Ordering Fails with 2 Template Parameters | So given the following template functions with partial specialization
template<typename T>
void foo(vector<T> &in) {
cout << "vector" << endl;
}
template<typename T>
void foo(T &in) {
cout << "scalar" << endl;
}
int main(int arc, char *argv[]) {
vector<double> a;
double b;
foo(a);
foo(b);
... | This seems to be related to this defect which is fixed in the latest version of the compiler. Workarounds are to explicitly set all arguments of the template or to use functor instead:
template<typename U>
struct foo2 {
template<typename T>
void operator()( std::vector<T> &in ) {
U a;
cout << "v... |
3,086,770 | 3,089,632 | What algorithms to use for image downsizing? | What algorithms to use for image downsizing?
What is faster?
What algorithm is performed for image resizing ( specially downsizing from big 600x600 to super small 6x6 for example) by such giants as flash and silver player, and html5?
| Bilinear is the most widely used method and can be made to run about as fast as the nearest neighbor down-sampling algorithm, which is the fastest but least accurate.
The trouble with a naive implementation of bilinear sampling is that if you use it to reduce an image by more than half, then you can run into aliasing a... |
3,086,805 | 3,086,871 | What I am doing wrong with c++ maps? (scary memory errors) | I am new to C++ and I'm having trouble using a map correctly in class that I'm writing. Basically, when I make a new Block object in a test program and call its write method, the program totally shits itself and gives me a double free or corruption error. What is weird is that everything works fine if I uncomment that ... | Are you sure the error isn't when you call read()? After all, your constructor assigns page[4] to 0xfeedface, an arbitrary place in memory that could point to anything. If you try to then read that location in memory, bad things may happen.
I would try to avoid creating pointers out of arbitrary addresses. Instead, ... |
3,086,949 | 3,086,979 | stringstream was not declared in this scope | I'm having problem with stringstream.my visual studio nor linux g++ can understand stingstream. I've added sstream but it does'nt solve anything. I've worked with it before and really don't know what's up with it now?
#include <sstream>
#include <stdlib.h>
#include "SymbolTable.cpp"
#include "setjmp.h"
using namespace ... | If you include #include <sstream> then you must also reference the class by:
std::stringstream or declare using namespace std; before using it.
If you post more information we could provide more detailed help.
|
3,087,025 | 3,087,676 | Need help designing an inter-process comm layer | I have several process in my system that need to communicate with each other.
Some of the processes need to pass chunks of data 60 times per second continuously,
and some are very sporadic.
Most of the processes are in C#, one is C++.
All running on the same windows 7 machine.
Right now each process has it's own differ... | I would suggest using ICE, which supports remote objects and message passing. It will have no problem meeting your rates and bandwidth needs. It's also cross platform and supports languages other then just C# or C++, giving you more languages choices for other components.
|
3,087,223 | 3,087,251 | Having trouble understanding this error creating a thread | HANDLE hThread;
DWORD dwThreadId;
hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
0, // argument to thread function
0,... | Clicking on the error takes you to the last parameter because the go-to-error function can only go by statements, and the entire function call is one statement.
Basically, your problem is that MyThreadFunction has the wrong signature. It should be unsigned long __stdcall MyThreadFunction(void*) (or the equivalent there... |
3,087,268 | 3,088,193 | question with longjmp | I want to use longjmp to simulate goto instruction.I have an array DS containing elements of struct types (int , float, bool ,char). I want to jump to the place labled "lablex" where x is DS[TOP].int_val. how can I handle this?
sample code :
...
jmp_buf *bfj;
...
stringstream s;s<<"label"<<DS[TOP].int_val;
bfj = (jmp_b... | You probably don't want to use longjmp at all but I hate it when people answer a question with "Why would you want to do that?" As has been pointed out your longjmp() usage is wrong. Here is a simple example of how to use it correctly:
#include <setjmp.h>
#include <iostream>
using namespace std;
jmp_buf jumpBuffer... |
3,087,274 | 3,087,417 | Is int guaranteed to be 32 bits on each platform supported by Qt, or only qint32? | I remember reading somewhere that Qt guarantees the size of some data types on supported platforms. Is it that int will be at least 32 bits everywhere, and qint32 will be exactly 32 bits everywhere? Or something else?
C++ guarantees that int will be at least 16 bits, and some Qt structures like QRect and QPoint use int... | The size of an integer type is up to the compiler. I don't think there's a guarantee that plain int will be of a precise size. But you can make sure you know it's not what you want by adding this line to the beginning of your main():
if(sizeof(int) != 4) {
throw std::runtime_error("int is not 32-bit");
}
|
3,087,364 | 3,087,378 | Iterating std::string elements | does it take constant time to move the iterator to elements of string in following:
std::string str // string of size 100 MB
std::string::iterator iter = str.begin();
std::advance(iter, str.size()-1);
would it take constant time as in searching by index?
char c = str[str.size()-1];
| Yes, that's correct. This is guaranteed by the C++ standard (§24.3, Iterator operations):
Since only random access iterators
provide + and - operators, the library
provides two function templates
advance and distance. These function
templates use + and - for random
access iterators (and are, therefore,
co... |
3,087,422 | 3,087,833 | How do the variable length fields in the windows EVENTLOGRECORD structure work? | I've tried, with little success, to identify how the variable length portion of the EVENTLOGRECORD data works.
Winnt.h defines the structure, and the following data, as follows:
typedef struct _EVENTLOGRECORD {
DWORD Length; // Length of full record
DWORD Reserved; // Used by the service
DWORD Record... |
So can someone explain how to determine the "SourceName" length from the EVENTLOGRECORD structure,
From what I can see, SourceName[] and Computername[] are one behind each other, separated by a '\0', with the first starting right behind DataOffset, and the second starting right behind the '\0' of the first, and goin... |
3,087,499 | 3,087,531 | preventing memory leak (case-specific) | Consider the following situation:
SomeType *sptr = someFunction();
// do sth with sptr
I am unaware of the internals of someFunction(). Its pretty obvious that the pointer to the object which someFunction() is returning must be either malloc'ed or be a static variable.
Now, I do something with sptr, and quit. clearly ... | You need to read the documentation on someFunction. someFunction needs to clearly define the ownership of the returned pointer (does the caller own it and need to call delete or does someFunction own it and will make sure the the object is destructed sometime in the future).
If the code does not document it's behavior... |
3,087,634 | 3,087,659 | How do I find the number of bytes used by a pointer? | I have a pointer (uint8_t *myPointer), that I pass as parameter to a method, and then this method sets a value to this pointer, but I want to know how many bytes are used (pointed at ?) by the myPointer variable.
Thanks in advance.
| The size of the pointer: sizeof(myPointer) (Equal to sizeof(uint8_t*))
The size of the pointee: sizeof(*myPointer) (Equal to sizeof(uint8_t))
If you meant that this points to an array, there is no way to know that. A pointer just points, and cares not where the value is from.
To pass an array via a pointer, you'll need... |
3,087,822 | 3,087,858 | Passing row of static 2-d array to function in C++ | This is a really elementary question. Nonetheless, I haven't found a solution after studying dozens of semi-relevant examples online.
I have a two-dimensional array of doubles whose size is known at compile time: double demPMFs[ NUM_DEM_PARAMS ][ NUM_AGE_CATEGORIES ]. Array entries are populated by input files early in... | Instead of using array[index][], use array[index]:
#define LSPAN_PMF demPMFs[0]
// ... etc.
But why obfuscate working with arrays so much? Using named indices would be much clearer:
enum {
IndexLspan,
IndexFledge,
// ...
};
int calcDeath( double demPMFs[][ NUM_AGE_CATEGORIES ] ) {
int age_death = rmul... |
3,088,058 | 3,088,306 | What's the point of using boost::mem_fn if we have boost::bind? | I'm having a look at the Boost libraries that were included in C++'s Technical Report 1 and trying to understand what each does.
I've just finished running an example for boost::mem_fn and now I'm wondering what's the point of using it instead of the better boost::bind. As far as I understand, both of them return a fu... | mem_fn is much smaller than bind, so if you only need the functionality of mem_fn it's a lot less code to pull in.
|
3,088,198 | 3,088,320 | How to handle state transitions and yet replace "if" statements with polymorphic types? | Recently I was listening to a tech talk on clean coding. The speaker was a test engineer, who emphasized on avoiding the "if" statements in the code and use polymorphism as much as possible. Also he advocated against global states.
I quite agree with him, yet i need a clarification on replacing the global state and "if... | If you are using Qt, take a look at The Qt State Machine Framework and the State Machine Examples. No need to re-invent the wheel when your framework already provides a sports car :)
|
3,088,231 | 3,088,886 | How to achieve better efficiency re-inserting into sets in C++ | I need to modify an object that has already been inserted into a set. This isn't trivial because the iterator in the pair returned from an insertion of a single object is a const iterator and does not allow modifications. So, my plan was that if an insert failed I could copy that object into a temporary variable, erase... | I hope it isn't bad form to answer my own question, but I would like it to be here in case someone else ever has this problem. The answer of why my attempt seg faulted was given my academicRobot, but here is the solution to make this work with a set. While I do appreciate the other answers and plan to learn about maps,... |
3,088,236 | 3,088,477 | Duplicate symbol error associated with const char * [] declaration | I'd love help diagnosing the source of a duplicate symbol error that I'm receiving when I try to compile with g++ 4.2.1.
The specific error is
ld: duplicate symbol _SOCIODEM_FILENAMES in /var/folders/c+/c+eq1Qz1Feye7vxs5mQOUE+++TI/-Tmp-//ccP3yVgF.o and /var/folders/c+/c+eq1Qz1Feye7vxs5mQOUE+++TI/-Tmp-//cc1NqtRL.o
co... | For some reason none of the answers so far cared to explain the difference between your integer NUM_SOCIODEM_FILES object and array SOCIODEM_FILENAMES object. The latter triggers the linker error for the reasons already explained: because you include you header file into multiple implementation files. Yet, the former w... |
3,088,395 | 3,088,413 | How do I set the windows system clock to the right local time using C++? | Right now I do something like this:
SYSTEMTIME st;
st.wHour = 6;
st.wMinute = 23;
BOOL result = SetSystemTime(&st);
The goal is to get it to show that exact time on my local machine. When I run the program it changes it to 8:23 instead of 6:23. How can I get it to show the correct local time?
| SetSystemTime() expects the provided time to be in UTC. If you want to set the time using the local time, use SetLocalTime().
|
3,088,464 | 3,088,474 | Can C++ assignment operators be free functions? | I'm trying something like this:
Foo & operator=(Foo & to, const Bar &from);
But I'm getting this error:
E2239 'operator =(Foo &, const Bar &)' must be a member function
Are there limitations on which operators can/cannot be defined as Free Functions, and if so, why?
| The assignment operator must be a non-static member function and must have exactly one parameter:
An assignment operator shall be implemented by a non-static member function with exactly one parameter (C++03 13.5.3/1).
operator(), operator[], and operator-> must also be implemented as non-static member functions.
C... |
3,088,555 | 3,088,615 | How do I set the date to the next weekday of my choice using c++? | I would like to determine the next date that has a day of the week value equal to something I specify.
For example, today is 6/21/2010 and the day of week value is 1 b/c today is a Monday. How do I find the next date with let's say a day of week value of 3.
I would like to consider all cases that come close to the end ... | You can stuff your values into a struct tm, and then normalize them with a call to mktime. This will ignore the day of week and day of year on input, and normalize the other values. For example, you can feed it an input of February 31st, and it'll convert that to March 3rd (or March 2nd for a leap year).
To use this, t... |
3,088,557 | 3,088,731 | Are you aware of any lexical analyzer or lexer in Qt? | Are you aware of any lexical analyzer or lexer in Qt? I need it for parsing text files.
| It is kinda interesting how Qt has evolved into an all-compassing framework that makes the programmer that uses it believe that anything that is useful has to start with the letter Q. Very dot-netty. Qt is just a class library that runs on top of the language, it doesn't preclude using everyday libraries that get a j... |
3,088,581 | 3,088,889 | segfault when trying to access a string member of a class | I have a class Message that has a std::string as a data member, defined like this:
class Message
{
// Member Variables
private:
std::string text;
(...)
// Member Functions
public:
Message(const std::string& t)
: text(t) {}
std::string getText() const {return text;}
... | My guess is that by the point you use it->getText(), the iterator is NULL. Add a check it != messageLog.end() when you walk the array, and before calling it->getText().
|
3,088,607 | 3,088,678 | How do I concurrently download and convert a binary file using threads? | I have a program that downloads a binary file, from another PC.
I also have a another standalone program that can convert this binary file to a human readable CSV.
I would like to bring the conversion tool "into" the download tool, creating a thread in the download tool that kicks off the conversion code (so it can st... | This is a classic case of the producer-consumer problem with the download thread as the producer and the conversion thread as the consumer.
Google around and you'll find an implementation for your language of choice. Here are some from MSDN: How to: Implement Various Producer-Consumer Patterns.
|
3,088,725 | 3,088,913 | (C++)Code:: blocks does not recognize QT4 classes | So far I have worked in the console and a few days ago decided to try the QT GUI.
I downloaded the QT SDK , install it, adjust the location of QT and
set up the PATH Environment Variable -> per the instructions on the site.
I opened a new Qt4 project in Code:: Blocks-in and it seemed that everything was OK.
There is by... | You need to either spend time monkeying with the default include search path, or else just provide a more explicit path the header you want to include. I was able to reproduce your problem with Code::Blocks 10.05 (with bundled gcc) on Windows XP/32 and a previously installed Qt 4.6. Here is the slightly changed versi... |
3,088,783 | 3,088,849 | Suitability of C# for clustered calculation-heavy apps? | I'm preparing to write a photonic simulation package that will run on a 128-node Linux and Windows cluster, with a Windows-based client for designing jobs (CAD-like) and submitting them to to the cluster.
Most of this is well-trod ground, but I'm curious how C# stacks up to C++ in terms of real number-crunching ability... | The optimisation techniques employed by C# and native C++ are vastly different. C# compilers emit IL, which is only marginally optimised and then JIT'ed to binary code when it is about to execute for the first time. Most of the optimisation work happens inside the JIT compiler.
This has pros and cons. JIT has time budg... |
3,088,919 | 3,089,123 | Expected specifier-qualifier-list before... Error in C++/Objective-C iPhone project | So I'm going through the first tutorial in O'Reilly's iPhone 3D Programming book. At this point in the tutorial, it pulls all the OpenGL ES stuff into a seperate c++ interface. I have followed the book to the letter, as far as I can tell, yet I can't seem to figure out this compiler error. I'm fairly new to C++ (mostly... | This error message e.g. occurs if one of your two headers gets included in a plain Objective-C source file, which doesn't know anything about handling C++ code.
To allow GLView to be used from plain Objective-C sources, use only a forward declaration for the rendering engine and don't include the C++ header in GLView.h... |
3,088,955 | 3,088,990 | Recommendations for Secure TCP Connections For Consumer Application | I'm designing a training program in C++ that will be distributed to a large number of facilities, most of which won't have much in the way of an IT staff. The program connects via a TCP connection to a central database which stores various pieces of data for research and evaluation purposes.
The problem I have is that ... | As long as all your machines are XP+, with two versions of OpenSSL you should be ready, one for 32bits and one for 64bits. Just provide two separate installers and that should be it. There's no need to compile for each machine.
Just remember to include the Visual C++ redistributable package in your installer as well.
... |
3,088,987 | 3,089,069 | interface forwarding from member variable using C++ templates | How do I say:
template<typename T>
class X {
// if T has method x(), define
// Y x() { return t.x() }
T t;
};
| Just define it.
If X::x isn't called, then T::x doesn't have to exist either. If X::x is called and T::x doesn't exist, the error message will point to the use of X::x. Most compilers would use wording along the lines of: "Unknown identifier x while compiling Y X<Something>::x(void) within this context: whatever call... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.