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 |
|---|---|---|---|---|
626,511 | 626,594 | CComboBox automatically selects text after call to MoveWindow | I'm currently experiencing a very strange problem with a CComboBox used within a CFormView.
After adding strings to the combobox (created with WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWN | CBS_SORT | CBS_AUTOHSCROLL), I'm selecting an entry via CComboBox::SetCurSel and resize the combobox via MoveWin... | Selecting all the text is standard Windows behavior when a combo box gets focus. I guess the MoveWindow is resetting the focus on the control.
Try using CComboBox::SetEditSel to remove the selection after MoveWindow.
|
626,708 | 626,731 | How to recover from lost source code? | I have a one-function DLL that exports GetHash(). However, the source code for this DLL is lost. I need to integrate this code into my MSVC++ project.
I know that there are some shareware tools for doing this, but I think that I can do it manually.
What do I need to do, to accomplish this manually?
| In a project that you build, reference the dll and call the hash function.
Run the code in the debugger and step in and disassemble the function and translate it back into a high level language.
If this isn't good enough, disassemble code into a series of functions you can implement with ASM blocks.
|
626,744 | 626,890 | Is there a way to automatically avoiding stepping into certain functions in Visual Studio? | I'm aware of the "Enable just my code" debug option, but that only works for managed code.
I'm looking for a way to step into a function call without having to step through, for example, an STL string cast operator because there is an implicit conversion from a char* to a string in one of the function's parameters.
| I found this blog entry which has a solution. Although I'd prefer to be able to say "don't step into anything that isn't part of this project", this looks workable.
EDIT: After looking at a few blogs and newsgroups, the method is to add an entry for each function that you don't want to step into under this registry key... |
626,849 | 626,884 | Initialize COM object / Translate VB code to C++ | Can anybody translate the following code to C++? Is this possible at all or are there vital information missing?
Dim Laser As Object
Sub EnableLaser
‘ Create a laser object if it hasn’t been done yet
If Laser Is Nothing Then
Set Laser = CreateObject("NWLaserXControl.NWLaserX")
End If
If Laser.In... | // if (CoInitialize(0) == S_OK)
{
CComPtr<INWLaserX> pMyPtr = NULL;
CLSID clsid = IID_NULL;
CLSIDFromProgID("NWLaserXControl.NWLaserX");
if (pMyPtr.CoCreateInstance(clsid) == S_OK)
{
pMyPtr->put_RepRate(10);
pMyPtr->put_LaserEnabled(TRUE);
}
// CoUnInitialize();
}
|
626,865 | 626,973 | How to keep implementation/maintenance costs low in Pro*C? | Having experienced the horror that is Oracle Pro*C, when dealing with dynamically specified columns, and the need for bulk operations (ANSI METHOD 4), I simply must ask:
What Ideas/Techniques can you share which makes it easier to develop/test/debug/maintain C and C++ CRUD applications which use ProC or ProC++? I am ... |
Pull as much of the Oracle stuff out of the C code as you can and stick it in database PL/SQL packages/procedures/functions.
Isolate (to the extent possible) the Oracle functionality in your C code. The less scattered your oracle calls are around your C code the better. Even better, have a library/DLL that contains th... |
627,131 | 627,889 | GetDiskFreeSpaceEx reports wrong number of free bytes | __int64 i64FreeBytes
unsigned __int64 lpFreeBytesAvailableToCaller,
lpTotalNumberOfBytes,
lpTotalNumberOfFreeBytes; // variables used to obtain
// the free space on the drive
GetDiskFreeSpaceEx (Manager.capDir,
(PULARGE_INTEGER)&lpFreeBytes... | I have a single-user machine with no disk quota in operation. I posted your code into a dialog based MFC application and ran it, with the single proviso that I used "C:\" as the lpDirectoryName parameter so I could compare against the drive free space as reported by the system. That seemed logical as free space is only... |
627,143 | 629,972 | How to handle notify messages in child & parent classes? | I have a custom CTabCtrl which I am trying to customize (to automatically change pages).
If I handle ON_NOTIFY_REFLECT(TCN_SELCHANGE, ...) in my tab control, ON_NOTIFY(TCN_SELCHANGE, ...) is not received by the parent class.
How can I receive both notify messages in the child and parent classes?
Currently I am using a... | I've found the answer:
http://msdn.microsoft.com/en-us/library/eeah46xd.aspx
Basically you have to use ON_NOTIFY_REFLECT_EX and then return FALSE from your function to enable the parent notify message to be fired.
|
627,218 | 630,070 | Is there a plugin that integrates to CPPUnit with VS2008 or Eclipse CDT? | We have some projects that have CPPUnit tests that are build and run using an ant script to build them all (right now we're using Borland C++, but we're moving to VS2008).
The problem is that the interface to run and see the result of tests is unpleasant (command prompt). It would be awesome to have them run inside ecl... | Their doesn't seem to be a test runner for within Visual Studio, just the MfcTestRunner and the QtTestRunner.
For Visual Studio, Resharper and TestDriven.Net are the usual suspects to first look for test runners, but both don't have support for CPPUnit.
|
627,273 | 627,293 | Will auto_ptr protect against this? | I am not quite clear if auto_ptr will help me in this case:
class A
{
A(const B& member)
: _member(B)
{};
...
const B& _member;
};
A generateA() {
auto_ptr<B> smart(new B());
A myA(*smart);
return myA;
}
Will the myA._member reference be valid when smart leaves its enclosing scope? If auto_ptr isn... | It won't help you. _member will become a dangling handle. This is because auto_ptr guarantees destruction at end of scope: no more, and no less.
There are 2 possible answers.
You can make _member's type boost::shared_ptr<const B>.
Alternatively, if class B is small, copyable, monomorphic, and object identity doesn't n... |
627,319 | 627,334 | how do I get a process to reload itself in linux? | I have a service, say foo, written in C++, that runs as root. There is the usual scrip, /etc/init.d/foo start|stop|restart.
At certain times, foo needs to reload itself. Normally after an upgrade has finished. But doing things like:
system("/etc/init.d/foo restart")
doesn't work since as soon as restart kills foo, ... | Have you considered the exec[*] family yet? Here's one -- execve.
|
627,512 | 627,546 | Help with declaring C++ structure, with a float array as one of its members | I was wondering if anyone could spot what is wrong with my structure declaration and use. At the moment I have a structure and wish to store float array as one of it's members.
My code:
struct Player{
float x[12];
float y[12];
float red,green,blue;
float r_leg, l_leg;
int poly[3];
bool up,down;
};
I then tried fillin... | Arrays decay to pointer-to-first-element of the array in most contexts as is the case with xcords and ycords. You cannot initialize the struct like this. So, you have to initialize the members explicitly:
Player player = {
{1,1,1,1,1,1,1,1,1,1,1,1 }, // xcords
{1,1,1,1,1,1,1,1,1,1,1,1 }, // ycords
... |
628,410 | 628,421 | error: X may be used uninitialized in this function in C | I am getting this error
error: Access.Core may be used uninitialized in this function
And this is my code:
static int FirstTime = 1;
MyStruct Access;
if (FirstTime) {
FirstTime = 0;
Access = Implementation();
DoSomething(Access);
}
if(Other_Variable) {
Access = Implementation2();
DoSomething(Ac... | Make Access like this (and remove FirstTime and the if):
static MyStruct Access = Implementation(this_b);
The reason you get this warning is because static variables survive one function call. Their value is retained across all function calls (without regard to which thread calls that function). So, FirstTime will con... |
628,526 | 628,554 | Is short-circuiting logical operators mandated? And evaluation order? | Does the ANSI standard mandate the logical operators to be short-circuited, in either C or C++?
I'm confused for I recall the K&R book saying your code shouldn't depend on these operations being short circuited, for they may not. Could someone please point out where in the standard it's said logic ops are always short-... | Yes, short-circuiting and evaluation order are required for operators || and && in both C and C++ standards.
C++ standard says (there should be an equivalent clause in the C standard):
1.9.18
In the evaluation of the following expressions
a && b
a || b
a ? b : c
a , b
using the built-in meaning of the operators in th... |
628,588 | 628,609 | Renaming executable causes error when run | I have created a small daemon (basically a console application that hides the console and runs).
I need to send it to a user and have tried renaming the executable with a different extension, emailing it to the user, and having them rename it to the correct name.
This seems to work when I email it to myself to test i... | You are missing some dlls.
You can figure out exactly which ones using dependency walker.
You could also install the Visual Studio Re-distributable package (x86) or Visual Studio Re-distributable package (x64) and that will probably fix your problem too.
|
628,790 | 628,867 | Have a good hash function for a C++ hash table? | I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking what's a good hash function "in general". I've considered CRC32 (but where to find good implementation?) and a few cryptography algorithms. My table,... | Now assumming you want a hash, and want something blazing fast that would work in your case, because your strings are just 6 chars long you could use this magic:
size_t precision = 2; //change the precision with this
size_t hash(const char* str)
{
return (*(size_t*)str)>> precision;
}
CRC is for slowpokes ;)
Explan... |
628,933 | 684,144 | CStatusBarCtrl GetItemRect XP Manifest | When using a CStatusBarCtrl in MFC I use GetItemRect to get the bounds of each item within the CStatusBar.
However I am seeing a problem now I use an XP manifest in the exe. That it will not return a correct rectangle so I no longer identify correctly when the mouse is in the far right of the control.
The problem can b... | My first guess would be differences between 'THEMES' in Vista and XP. Remember, if you are using a CFrameWnd there is a gripper control in what would be your last pane in the far right of the status bar. So, it looks as though changes in the ComCtl32.dll may account for this, thus, giving you a smaller rect. I assum... |
629,017 | 629,063 | how does array[100] = {0} set the entire array to 0? | How does the compiler fill values in char array[100] = {0};? What's the magic behind it?
I wanted to know how internally compiler initializes.
| It's not magic.
The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).
The behavior of this... |
629,018 | 629,336 | Advantage of porting vc6 to vc2005/vc2008? | I was asking my team to port our vc6 application to vc2005, they are ready to allot sometime to do the same.Now they need to know what is the advantage of porting.
I don't thing they really understand what does it mean to adhere to standard compliance.
Help me list out the advantage to do the porting.
Problem I am faci... | Advantages:
More standards compliant compiler. This is a good thing because it will make it easier to port to another platform (if you ever want to do that). It also means you can look things up in the standard rather than in microsoft's documentation. In the end you will have to upgrade your compiler at some point in... |
629,085 | 629,303 | unresolved external symbol _CLSID_ScenicIntentUIFramework with GUID | I'm trying to build a ribbon app in visual studio and I got that linker error. After looking through the headers, I noticed that CLSID_ScenicIntentFramework is defined as extern const CLSID. The think is, I can't seem to figure out which library I need to link to (or other header i need to import?).
I'd really apprecia... | Often times, you need to link to an import library (.lib file) that contains the definitions of the class ids and interface ids for the library you are using. Alternatively, you can use the __uuidof keyword that can get the associated GUID for an attributed object (a class or interface).
__uuidof(ScenicIntentFramework)... |
629,141 | 629,149 | why bit-fields for same data types have less in size compared to bit-fields for mix-data types | I am curious to know why bit fields with same data type takes less size than with mixed
data types.
struct xyz
{
int x : 1;
int y : 1;
int z : 1;
};
struct abc
{
char x : 1;
int y : 1;
bool z : 1;
};
sizeof(xyz) = 4
sizeof(abc) = 12.
I am using VS 2005, 64bit x86 machine.
A bit machine/comp... | Alignment.
Your compiler is going to align variables in a way that makes sense for your architecture. In your case, char, int, and bool are different sizes, so it will go by that information rather than your bit field hints.
There was some discussion in this question on the matter.
The solution is to give #pragma direc... |
629,205 | 647,087 | Need help to display Japanese Text using GDI+ without installing East Asian Language pack in Windows XP | I am writing a Japanese language quiz program and I don't want to require people to install the East Asian language pack for Windows XP. I am using GDI+ for drawing text. I tried downloading a free Unicode font and using that to draw text. I tested it on my computer (with East asian pack installed) and it displayed ... | I was wrong. If you have a font that includes Japanese Characters it will display correctly in Windows XP even if East Asian language Pack is not installed.
If you have the East Asian Language Pack installed and if your font doesn't support Japanese characters, Windows will pick from between one of two fonts that it t... |
629,433 | 629,448 | How to initialize nested structures in C++? | I have created a couple of different structures in a program. I now have a structure with nested structures however I cannot work out how to initialize them correctly. The structures are listed below.
/***POINT STRUCTURE***/
struct Point{
float x; //x coord of point
float y; ... | You initialize it normally with { ... }:
Player player = {
vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ),
vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ),
5, 1, 5, 1, 5, 1, 5, 1,
1.0f,1.0f,1.0f, //red, green, blue
0.0f,0.0f, ... |
629,559 | 629,743 | A weird memory leak problem | I use an ActiveX control which is just a HTTP handler. It sends out an HTTP request, gets the response and fires an event to the user. When the user is not requesting the ActiveX control is pretty much dormant. It just waits for a user request to send another HTTP request.
As long as the window in which the OCX resides... | Assuming that the HTTP string is passed down via BSTRs, you might be running into BSTR caching. To verify, you'll want to set the environment variable OANOCACHE to 1 or call OaSetNoCache() directly. The environment variable should be easier to test with.
|
629,741 | 630,104 | How to initialize a IMimeMessage object from IStream | Given an empty MimeMessage created with e.g. MimeOleCreateMessage function, how can I initialize it from an IStream / data buffer, which contains the complete message text?
| If I'm not wrong IMimeMessage returned by MimeOleCreateMessage supports IPersistStream stream then you have Load & Save methods.
|
629,894 | 629,978 | Function-Level Linking (/Gy switch in VC++) - What is it good for? | What is there to gain from the use of this switch in a large VS solution (200 VC projects)?
From what I understand this mainly affects the size of the resulting binaries; but aside from smaller binaries, could FLL also help in reducing dependencies between projects?
How does FLL usually affect build times?
I'd also app... | Since you linked MSDN's explanation, you know that /Gy ensures that all functions are packaged in their own COMDAT. The main advantage of this is that if you have identical functions the linker can collapse them all down into one actual piece of code ("COMDAT folding"). This can have very large impacts when you have ... |
629,961 | 850,464 | How can I set ccshared=-fPIC while executing ./configure? | I am trying to build Python 2.6 for QGIS on RHEL 5.
During the making of QGIS I get the following error:
Linking CXX shared library libqgispython.so
/usr/bin/ld: /usr/local/lib/python2.6/config/libpython2.6.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recom... | Run configure with --enable-shared. Then -fPIC will be included as part of the shared flags.
|
630,432 | 630,454 | Where can I find a ZwCreateFile example for C++? | I am looking for an example to read an already opened COM port, the only thing that I have found is an application called PORTMON that refers to a method called ZwCreateFile.
| codeproject.com - is a nice site for looking examples.
http://www.codeproject.com/KB/system/chaiyasit_t.aspx
edit:
msdn have information too
http://msdn.microsoft.com/en-us/library/aa363424.aspx
|
630,920 | 630,994 | Store pointers to member function in the map | I'd like to map string to an instance member functions, and store each mapping in the map.
What is the clean way of doing something like that?
class MyClass
{
//........
virtual double GetX();
virtual double GetSomethingElse();
virtual double GetT();
virtual double GetRR();
//........
};
class Proc... | Looks fine to me, but for the fact that descrToFuncMap needs to be declared static if you intend to initialise it from inside the static function Initialize().
If you want to make sure that Initialize() gets called, and gets called just once, you can use the Singleton pattern. Basically, if you aren't doing multithrea... |
630,950 | 630,960 | Pure virtual destructor in C++ | Is it wrong to write:
class A {
public:
virtual ~A() = 0;
};
for an abstract base class?
At least that compiles in MSVC... Will it crash at run time?
| Yes. You also need to implement the destructor:
class A {
public:
virtual ~A() = 0;
};
inline A::~A() { }
should suffice.
If you derive anything from A and then try to delete or destroy it, A's destructor will eventually be called. Since it is pure and doesn't have an implementation, undefined behavior will ensue... |
631,145 | 631,177 | Why param needs two arguments in following case: | I am sort of confused by this:
istream_iterator<string> ii(is);
istream_iterator<string> eos;
vector<string> param (ii, eos);
| One for start and one for end
RANDOM DATA BEGIN ITERATOR USEFUL DATA END ITERATOR RANDOM DATA
Without "eos", how would the vector know when it has reached the end?
|
631,201 | 631,287 | Why is a second cin.ignore() necessary? | I've noticed that whenever I write a program that uses std::cin that if I want the user to press Enter to end the program, I have to write std::cin.ignore() twice to obtain the desired behavior. For example:
#include <iostream>
int main(void)
{
int val = 0;
std::cout << "Enter an integer: ";
std::cin >> v... | Discl: I'm simplifying what really happens.
The first serves to purge what the extraction operator (>>) hasn't consumed.
The second waits for another \n.
It is exactly the same when we do a std::getline after an extraction: a the_stream::ignore(std::numeric_limits<streamsize>::max(), '\n'); is required before the call ... |
631,282 | 631,393 | const pointer as a constructor argument | This is an odd one. Note this is cut down example code, and misses out destructors deliberately).
template <class f, class g> class Ptr;
class RealBase
{
};
template <class a, class b, class c = Ptr<a,b> >
class Base : public RealBase
{
public:
Base(){};
};
template <class d, class e>
class Derived : public Bas... | I think you need to define a separate class to wrap pointers to const, since not only the arguments of the constructor, but also the return types of the operators should be changed to const versions. If you make the ConstPtr a friend of Ptr, this should work out quite nicely:
template<...>
class ConstPtr {
const Base... |
631,380 | 647,113 | Is it wise to provide access to weak_ptr in a library interface? | I have written a library that exposes references to several related object types. All of these objects have their lifetimes managed by the library internally via boost::shared_ptr
A user of the library would also be able to know, by nature of the library, the lifetimes of any of the exposed objects. So they could sto... | If the smart_ptrs are already directly accessible to the library's users, then they've already got access to the weak_ptrs, simply via the corresponding weak_ptr's constructor. But if the smart_ptrs are all internal to the library, that's a different story.
In that case, I'd recommend letting each object pass out weak_... |
631,506 | 631,532 | Does Pre and post increment/decrement operators in C++ have same performance in a loop? | Consider following two examples.
class ClassOne
{
//class definition is here
};
std::vector< ClassOne > myListOfObjects;
std::vector< ClassOne >::const_iterator iter = myListOfObjects.begin();
Example 1:
for( ; iter < myListOfObjects.end(); **++iter**)
{
//some operations
}
OR
Example 2:
for( ; iter < myList... | As noted in this answer, pre is faster. They are only the same when you are dealing with primitives (int, char, etc.). In this case, they are calling overloaded operators.
|
631,633 | 631,767 | returning a 'pointer' which is required to be held by a smart pointer | I have a project which I would like to make more use of smart pointers. Overall, I have been successful in this goal. However, I've come across one things which I'm not sure what the "best practice" is.
Basically I would like to return a "pointer" from a function, but require that the user hold it in a smart pointer. N... | Using std::auto_ptr is the good practice, in fact such example was suggested
by Bjarne Stroustrup.
The move semantics of auto_ptr gives you right tools to deal with it.
For example:
auto_ptr<Foo> make_foo()
{
return auto_ptr<Foo>(new Foo);
}
Foo *raw_pointer=make_foo().release();
shared_ptr<Foo> shared_pointer=mak... |
631,661 | 631,699 | snprintf Format String security vulnerability issue | We have a Coverity bug for this line of code:
snprintf( tempStr, size, testStrings[testID], A2DtoV(testResults[testID].value),
A2DtoV(testResults[testID].min),A2DtoV(testResults[testID].max));
The error says:
non_const_printf_format_string: "format string is not a string literal,
potential security vulnerability if u... | Your code is fine.
The issue is that if you pass a string that is user controlled as a printf format string, security bugs can arise.
For instance, printf(userName);
Where userName is supplied by the user, a user can pass "%s", and get your function to start accessing data at a random address on the stack, which could ... |
631,664 | 631,728 | Accessing Environment Variables In C++ | I'd like to have access to the $HOME environment variable in a C++ program that I'm writing. If I were writing code in C, I'd just use the getenv() function, but I was wondering if there was a better way to do it. Here's the code that I have so far:
std::string get_env_var( std::string const & key ) { ... | There is nothing wrong with using getenv() in C++. It is defined by stdlib.h, or if you prefer the standard library implementation, you can include cstdlib and access the function via the std:: namespace (i.e., std::getenv()). Absolutely nothing wrong with this. In fact, if you are concerned about portability, eithe... |
631,770 | 631,824 | C++ select first not null element | [question update according to updated requirements]
I've implemented following function which should return either first not null element or throw an exception.
Also could you invent more classic and shorter name like 'max', 'min', 'pair'?
template <typename T>
T select_first_not_empty( const T& a, const T&b )
{
st... | you can try do next
template < typename T >
T get_valuable( const T& firstValue,
const T& alternateValue,
const T& zerroValue = T() )
{
return firstValue != zerroValue ? firstValue : alternateValue;
}
// usage
char *str = "Something"; // sometimes can be NULL
std::string str2 ( ge... |
631,783 | 631,791 | What is the use of having destructor as private? | What is the use of having destructor as private?
| Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private.
For instance, if you're doing some sort of reference counting thing, you can have the object (or manager that has be... |
631,808 | 631,861 | rules for inclusion in header files when using type in typedef | if I create
typedef double (MyClass::*MemFuncGetter)();
in a header file, do I need to include "MyClass.h" or would forward declaring suffice?
Header file:
#ifndef _TEST_
#define _TEST_
#include "MyClass.h" //do I need this?
//or I can just say class MyClass;
typedef double (MyClass::*MemFuncGetter)();
#endif
W... | You are fine with just the forward declaration of the class:
#ifndef _TEST_
#define _TEST_
class MyClass;
typedef double (MyClass::*MemFuncGetter)();
#endif
But note that by not including the whole class, the compiler has to do extra work to handle the cases when MyClass is a multiple-virtual inheritance mess, since... |
631,952 | 631,966 | Forward declare pointers-to-structs in C++ | I am using a 3rd party library that has a declaration like this:
typedef struct {} __INTERNAL_DATA, *HandleType;
And I'd like to create a class that takes a HandleType in the constructor:
class Foo
{
Foo(HandleType h);
}
without including the header that defines HandleType. Normally, I'd just forward-declare such... | Update:
I am using it in the implementation .cpp of Foo, but I want to avoid including it in my header .h for Foo. Maybe I'm just being too pedantic? :)
Yes you are :) Go ahead with forward declaration.
If HandleType is part of the interface there must be a header declaring that. Use that header.
Your problem is st... |
631,969 | 631,975 | Creating C++ DLLs with Visual Studio | I am creating a simple C++ DLL project using Visual Studio 2008 Express Edition.
I have a few classes inside a namespace, and a few non-static functions and constructors inside it are declared with __declspec(dllexport).
All those functions are implemented.
I also have an extern "C" BOOL APIENTRY DllMain function which... | I'd look up a little higher in the directory structure (the one that the solution is in) and see if your Debug/Release folders (with the DLL) are there.
I think the default is to put the actual DLLs in folders in the solution directory, not the project directory (I think the assumption is that you want all the DLLs t... |
632,805 | 633,225 | What's the cleanest way to walk and unwalk a std::vector using iterators? | I have a situation where I'm marching through a vector, doing things:
std::vector<T>::iterator iter = my_list.begin();
for ( ; iter != my_list.end(); ++iter )
{
if ( iter->doStuff() ) // returns true if successful, false o/w
{
// Keep going...
}
else
{
for ( ; iter != m_list.begin(); --iter ) // .... | While using reverse iterators via rbegin() and rend() works nicely, unfortunately I find that converting between reverse and non-reverse iterarotrs tends to be quite confusing. I can never remember without having to go through a logic-puzzle exercise whether I need to increment or decrement before or after the conversi... |
632,896 | 632,930 | What is the best way for distributed processes to communicate asynchronously? | I'm developing an application in which distributed components talk to one another over a network, in an asynchronous, pub/sub kind of way.
For this, I like the idea of sending XML over sockets - it's asynchronous, I don't need a server of any kind, and it can work locally or over a network. I would have to roll my own... | Instead of using XML it might be best to use an existing message passing framework. Have a look at libt2n or d-bus
But it you have used your own socket implementation in the past with good results i don't see a reason why you should change. If it ain't broke don't fix it :)
|
632,919 | 633,150 | How to make an icon button in C++ | I know how to draw a button in C++ but how would i make an icon on it can someone post source or give reference please? by SendMessage() or if not that way just please paste
Please need easier anwsers without so many files im new a bit
| If you use MFC then I would recommend you to use the following CButton method SetIcon:
CButton myButton;
// Create an icon button.
myButton.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_ICON,
CRect(10,10,60,50), pParentWnd, 1);
// Set the icon of the button to be the system question mark icon.
myButton.SetIcon( ... |
633,549 | 633,563 | How to copy the contents of std::vector to c-style static array,safely? | I need to manipulate data in fixed array involving mid insertion.
Rather than using memcpy,etc. I want to use vector. I have problem when I want
to copy the vector elements back to the c-style array.
Here's the code:
void tryvector()
{
using namespace std;
const int MAX_SIZE=16;
BYTE myarr[MAX_SIZE]={0xb0,0... | The problem is that you're adding things to the vector so it ends up with more elements than were in the myarr array that you initialized it with.
If you want to copy the vector back into the array, you'll need to size it down:
myvec.resize( MAX_SIZE);
Or you could limit the number of elements you copy back:
copy( myv... |
633,634 | 633,643 | Declaring class objects in a header file | I seem to be snagging on a fundamental but I can't find the solution anywhere. Anywho, will go ahead and explain.
I have a program consisting of three files; main.ccp, add.h, add.cpp.
I declare the class 'SA' in add.h and have all my functions defined in add.cpp.
additional.h
class SA {
...
public
int x;
} Obj1... | Define Obj1 and Obj2 in your .cpp instead of at .h
add.h
class SA {
...
public
int x;
};
main.cpp
#include "additional.h"
SA Obj1, Obj2;
int main() {
Obj1.x = 5;
...
}
If you want to declare Obj1 and Obj2 in your .h file, add extern in the .h file like so:
extern SA Obj1, Obj2;
but you should declare the... |
633,851 | 633,870 | Shouldn't Gdiplus::Image::GetWidth() and a bunch of other getters be "const"? | Why aren't they const?
I believe that's flawed API design. Or am I missing something?
UINT GetWidth();
UINT GetHeight();
...
vs.
UINT GetWidth() const;
UINT GetHeight() const;
...
| Hard to say. I'd agree, but perhaps there is something in the implementation that prevents them from being const, and that they didn't want to add overhead to hide. Nowdays we have the mutable keyword, but I think that is younger than this API.
Or maybe the designers of the API belong to the (sometimes shockingly large... |
633,881 | 633,905 | Algorithm for Counting Sorted Strings (Homebrew "uniq -c") | I have the following sorted data:
AAA
AAA
TCG
TTT
TTT
TTT
I want to count the occurrences of each String:
AAA 2
TCG 1
TTT 3
I know I can do that using uniq -c, but here I need to do extra processing on the overall C++ code that I have.
I am stuck with this construct (modified according to 'pgras' suggestion):
#includ... | You have to reset counter when tag is different from lastTag, and increment if it's the same... When the tag is different you can handle the previous tag with it's associated count value (before you reset count)...
|
634,087 | 646,510 | std::copy to std::cout for std::pair | I have next code:
#include <iostream>
#include <algorithm>
#include <map>
#include <iterator>
//namespace std
//{
std::ostream& operator << ( std::ostream& out,
const std::pair< size_t, size_t >& rhs )
{
out << rhs.first << ", " << rhs.second;
return out;
}
//}
int main()
{
std::map < ... | I've founded one new elegant way to solve this problem.
I've got many interest ideas when read answers:
wrap iterator, for transform std::pair to std::string;
wrap std::pair, for have a chance to overload operator<<(...);
use usual std::for_each with printing functor;
use std::for_each with boost::labda - looks nice, ... |
634,404 | 634,480 | Complete solution for writing Mac OS X application in C++ | I am looking for alternatives for my current box and Mac OS X seems very appealing.
My main area of interest is C++ programming. Currently I'm using Eclipse + CDT and g++ for creating my software; sometimes it is KDevelop.
I know that primary IDE for Mac is Xcode and primary language is Objective-C. I would like to avo... | If you want to use C++ instead of Objective-C, and still want to avoid an intermediate layer of libraries (such as QT), you can use Carbon.
I would use XCode instead of Eclipse simply because Eclipse is way slower when dealing with hardcore C/C++ programming (compiling, debugging, testing).
When I first started to prog... |
634,502 | 634,685 | How can I extract frames from videos (using DirectShow)? | I have to extract the frames from any video file that can be played using the standard windows media player into separate images. Can you provide me some info on how to proceed, what documentation/books to read, etc?
The language is C/C++.
Also, don't recommend any solution which involves GPL code, the software I have ... | I can recommend you the following excellent example on CodeProject. It shows you how to process frames from a camera source or an avi file.
|
634,662 | 634,705 | Non-static const member, can't use default assignment operator | A program I'm expanding uses std::pair<> a lot.
There is a point in my code at which the compiler throws a rather large:
Non-static const member, 'const Ptr std::pair, const double*>::first' can't use default assignment operator
I'm not really sure what this is referring to?
Which methods are missing from the Ptr cla... | You have a case like this:
struct sample {
int const a; // const!
sample(int a):a(a) { }
};
Now, you use that in some context that requires sample to be assignable - possible in a container (like a map, vector or something else). This will fail, because the implicitly defined copy assignment operator does som... |
634,680 | 636,024 | Converting indexed polygons to unindexed ones. Several problems have cropped up | Yet again I have some questions regarding polygon algorithms.
I'll try to explain my problem:
I am using a subset of a third party library called Geometric Tools(GT) to perform boolean operations on my polygons. To accomplish this I have to convert my internal polygon format to the format GT uses.
Our internal polygon... | You are effectively trying to find all cycles in an undirected graph where each cycle represents the edges of a unique polygon. This paper proposes a depth-first search (DFS) solution.
|
634,816 | 634,876 | C++ Header files - put them in one directory or merged in a tree structure? | I have a substantial body of source code (OOFILE) which I'm finally putting up on Sourceforge. I need to decide if I should go with a monolithic include directory or keep the header files with the source tree.
I want to make this decision before pushing to the svn repo on SourceForge. I expect a lot of people who use ... | Personally I would go with 2, or 3 if really pushed.
But whichever you choose, please make it crystal clear in the build instructions how to set up the include paths. Nothing dooms an open source project more than it being really difficult to build - developers want a quick out-of-the-box experience and if it involves... |
634,951 | 634,957 | C++ OpenSource project for beginner programmer? | I`m a beginner C++ programmer. And I want to pursue my career in system- and driver-programming.
Can you suggest me an opensource projects to I improve my skills in low-level development?
I am looking for a project with the following characteristic:
- on C\C++ language based
- a small project with a small amount of co... | Check the google summer of code projects page! These are all open source, and many of them are based on C/C++. Each project lists ideas that are aimed at outsiders / beginners.
Here is last year's page: http://code.google.com/soc/2008/ Google has not yet decided on which projects are participating this year, but this i... |
634,963 | 635,098 | A good bank of recursion solutions in C/C++/Java/C# | I saw this question, but the answers there are not very relevant.
A friend needs a bank of solved recursion problems to help him study for a test tomorrow.
He learned the issue theoretically, but is having problems grasping how to actually solve recursion problems. Do you know a good source of solved recursion problems... | This article explains recursion and has some simple C examples for traversing linked list and binary tree
|
635,225 | 635,236 | How do I call a member function pointer using a pointer to a constant object? | Here is an example of what I want to accomplish and how:
class MyClass
{
public:
void Dummy() const{}
};
typedef void (MyClass::*MemFunc)();
void (const MyClass * instance)
{
MemFunc func=&MyClass::Dummy;
// (instance->*func)(); //gives an error
(const_cast<MyClass *>instance->*func... | The error is in the line before. Change the typedef to
typedef void (MyClass::*MemFunc)() const;
To make it a pointer to a const member function type.
The difference might be more clear when considering this code and how it works:
typedef void FunctionType() const;
typedef FunctionType MyClass::*MemFunc;
A member-f... |
635,276 | 635,295 | Simple Thread Synchronization | I need a simple "one at a time" lock on a section of code. Consider the function func which can be run from multiple threads:
void func()
{
// locking/mutex statement goes here
operation1();
operation2();
// corresponding unlock goes here
operation3();
}
I need to make sure that operation1 an... | Critical sections will work (they're lighter-weight that mutexes.) InitializeCriticalSection, EnterCriticalSection, LeaveCriticalSection, and DeleteCriticalSection are the functions to look for on MSDN.
void func()
{
// cs previously initialized via InitializeCriticalSection
EnterCriticalSection(&cs);
oper... |
635,658 | 635,796 | What is the best way to declare a global variable? | In C++, say you want to declare a global variable to be used by many. How do you do it?
I commonly use declare and define in cpp file, and then use extern in other cpp file (and not headers).
I don't like this approach, and I am considering something along these lines:
In a header file:
some_file.h
Class MYGlobalClas... | Declare it in one header file (using extern), and define it in one .cpp (or whatever other extension) file. You may use a function and return a reference to a static variable like you showed to circumvent problems with construction order relative to other such namespace scope variables in other .cpp files. But remember... |
635,705 | 635,764 | Why does my Boost.Regex search report only one match iteration? | I am trying to find out how many regex matches are in a string. I'm using an iterator to iterate the matches, and and integer to record how many there were.
long int before = GetTickCount();
string text;
boost::regex re("^(\\d{5})\\s(\\d{8})\\s(.*)\\s(.*)\\s(.*)\\s(\\d{8})\\s(.{1})$");
char * buffer;
long length;
lon... | Heh. Your problem is your regex. Change your (.\*)s to (.\*?)s (assuming that's supported). You think you're seeing each line being matched, but in fact you're seeing the entire text being matched because your pattern is greedy.
To see the issue illustrated, change the debug output in your loop to:
cout << "[" << ma... |
635,807 | 635,819 | Can a string literal and a character literal be concatenated? | Why does name misbehave in the following C++ code?
string name = "ab"+'c';
How would the equivalent code behave in Java/C#?
| Try
std::string name = "ab" "c";
or
std::string name = std::string("ab") + c;
In C++, "ab" is not a std::string, but rather a pointer to a string of chars. When you add an integral value to a pointer, you get a new pointer that points farther down the string:
char *foo = "012345678910121416182022242628303234";
std... |
635,812 | 636,633 | How to keep together few inseparable text blocks in QTextEdit at the end of current page (throw all on the next page)? | i have a QTextEdit document which size is different by every print. In the middle of the document i have few blocks of text which are inseparable in the eyes of the user and i have to protect my blocks from splitting on two pages in case the document gets equivalent size. Have you got any solution?
| I am a great fan of Qt but I have not had an opportunity yet to use a QTextEdit. I would like to help though so I took a look through the documentation.
If you are using a sufficiently recent version of Qt you should find that a QTextEdit has an associated QTextDocument and it would seem that the functionality you seek... |
636,110 | 636,206 | does adding new member function into d pointer class break binary compatibility? | Will adding new member function into d pointer class definition break binary compatibility?
For example, will the new definition below break binary compatibility compared to the original? (side question, is there a tool that will tell me if a new .so breaks binary compatibility compared to the old .so? If not, how do... | No it does not.
You should understand how C++ builds its objects.
In your case it is just almost "POD" class with non-virtual member functions. These
functions do not affet the representation of object in memory. Thus new version
is binary compatible with old.
More then that, if you do not expose your "APrivate" class ... |
636,755 | 636,760 | How can I return a const ref a to local variable in C++? | I have a function for which I cannot change the function parameters. I need to return a const reference to a std::string created in this function. I tried to use boost shared_ptr, but this doesn't work. Why? How do I make this work?
const std::string& getVal(const std::string &key) {
boost::shared_ptr<std::string... | You can't return a reference to a local variable from a function with c++. Although in c++0x this is possible.
Allocate the string on the heap and manually cleanup later:
If you cannot change the function's interface, then you will need to create it on the heap and then manually delete it after.
//Remember to free the... |
636,810 | 637,640 | Mac OSX - Xcode Installation Directory | After Xcode has finished building is there a way to make it copy the executable to specific directory
~/Sites/cgi-bin/
I have the target Installation Directory set to the correct folder, with skip installation unchecked, but no luck.
Is there something i'm missing?
| Check the "Deployment Postprocessing" build setting in your target's Release configuration. Installation is normally done only with a command-line xcodebuild install, but setting Deployment Postprocessing makes it install on every build.
Ensure your user account has write privileges in the directory you want to install... |
636,829 | 636,834 | Difference between void main and int main in C/C++? | Does it matter which way I declare the main function in a C++ (or C) program?
| The difference is one is the correct way to define main, and the other is not.
And yes, it does matter. Either
int main(int argc, char** argv)
or
int main()
are the proper definition of your main per the C++ spec.
void main(int argc, char** argv)
is not and was, IIRC, a perversity that came with older Microsoft's C+... |
636,975 | 728,723 | ATL simple object wizard - "Object Xxx already exists" error | I am attempting to create a new COM object in my DLL using the ATL Simple Object Wizard in Visual Studio 2005.
I enter the short name for the object, and all of the other fields are derived.
However, when I click Next in the wizard, the following error message comes up:
Object 'IXxxInterfaceName' already exists
I have... | I never found out why the wizard determined that the object name existed already - I'm guessing something was cached somewhere that I couldn't track down.
In the end, I appended a 2 to the end of the interface name when creating it which allowed it to be added. Then I replaced all the occurrences of IXxxInterfaceName2... |
636,999 | 637,031 | DECLSPEC_NOVTABLE on pure virtual classes? | This is probably habitual programming redundancy. I have noticed DECLSPEC_NOVTABLE ( __declspec(novtable) ) on a bunch of interfaces defined in headers:
struct DECLSPEC_NOVTABLE IStuff : public IObject
{
virtual method1 () = 0;
virtual method2 () = 0;
};
The MSDN article on this __declspec extended attribute ... | The compiler strips out the only reference to the vtable, which would have been during construction of the class. Therefore, the linker can optimize it away since there is no longer a reference in the code to it.
Also by the way, I have made a habit of declaring an empty constructor as protected, and also using Micros... |
637,081 | 637,217 | How can I link a dynamic library in Xcode? | I am currently developing a program in Qt and it uses the library libqextserialport.1.dylib.
I build it and run in x-code and it spits back:
dyld: Library not loaded: libqextserialport.1.dylib
Referenced from: /Users/samuelreh/Desktop/QtOpenCV/build/Debug/QtOpenCV.app/Contents/MacOS/QtOpenCV
Reason: image not ... | If I understand your problem correctly, your app is building fine, no errors when linking, but when you try to launch it the library cannot be found.
That's not surprising, since the dylib file is in some arbitrary directory not on the system path. You either need to copy it into /usr/lib (probably not a good idea) or ... |
637,118 | 637,155 | std::stringstream strange behaviour | Some background information, for a homework assignment I had to write a polish notation calculator using binary trees, for this to work I had to parse command line input so that it would properly build the binary tree and then go over it to give a valid answer to the mathematical expression that was entered.
For the pa... | When you say:
iss.clear();
std::cout << "iss fail bit: " << iss.fail() << std::endl;
iss.get(op);
you are trying to read something that has already been read. You need to reset the streams read pointer:
iss.clear();
iss.seekg(0); // start again
std::cout << "iss fail bit: " << iss.fail() << std::endl;
... |
637,175 | 637,214 | Possible bug in _controlfp_s may not restore control word correctly | I've stumbled across either a problem with _controlfp_s (Visual Studio 2008), or my understanding of it. I thought the first out parameter returned the control flags before changes of the other parameters are applied. Seems it returns the flags after the change.
So, I thought the correct way to use it was like this:
... | According to MSDN:
If the value for mask is equal to 0,
_controlfp_s gets the floating-point control word. If mask is nonzero, a
new value for the control word is set:
For any bit that is on (equal to 1) in
mask, the corresponding bit in new is
used to update the control word. In
other words, fpcntrl = ((f... |
637,196 | 637,198 | How to Pass Decimal Value as Argument Correctly | I have this:
double myDecimal = static_cast<double>(atoi(arg_vec[1]));
cout << myDecimal << endl;
But why when I pass the argument like this:
./MyCode 0.003
It prints 0 instead of 0.003.
| atoi() converts to integer. You want atof().
Or you could use strtod().
|
637,441 | 637,548 | std::for_each, calling member function with reference parameter | I have a container of pointers which I want to iterate over, calling a member function which has a parameter that is a reference. How do I do this with STL?
My current solution is to use boost::bind, and boost::ref for the parameter.
// Given:
// void Renderable::render(Graphics& g)
//
// There is a reference, g, in sc... | This is a problem with the design of <functional>. You either have to use boost::bind or tr1::bind.
|
637,489 | 637,498 | What would be the correct design for keeping configuration settings in c++? | Say I have ini/json to store configuration setting of my desktop application,Will it be ok to have a static object with all property loaded at startup/when ever it is required or is there any other better alternative?
Since this is the very first time I am doing this ,so just wanted to know whether static object is fin... | Either way is fine.
If it was me, I would have it on construction of the config object.
cConfig Config("config.ini");
This Config class would load the settings found in the file. Any code can access the settings by doing
Config.Get("NumberOfFoobars")
For testability purposes, if there is no file in the construction,... |
637,695 | 637,737 | How efficient is std::string compared to null-terminated strings? | I've discovered that std::strings are very slow compared to old-fashioned null-terminated strings, so much slow that they significantly slow down my overall program by a factor of 2.
I expected STL to be slower, I didn't realise it was going to be this much slower.
I'm using Visual Studio 2008, release mode. It shows... | Well there are definitely known problems regarding the performance of strings and other containers. Most of them have to do with temporaries and unnecessary copies.
It's not too hard to use it right, but it's also quite easy to Do It Wrong. For example, if you see your code accepting strings by value where you don't n... |
637,729 | 639,102 | Making C++ library Avaiable to .Net | I need to make a large c++ library avaiable for use in .Net languages such as C#.
The library contains a large number of classes which can be broken into two groups. Refrence counted classes, which implement the IRefCounted abstract class and use a factory method to create them, and just plain classes using new/delete.... | C++/CLI wrappers are definitely the best option if you are only targetting Windows. They perform very well, are very easy to write and maintain, etc. But, as you said, this will not work on Mono. The issue is that the assembly that gets created is not a clr:pure assembly, but one that has mixed native and IL code, s... |
637,892 | 637,901 | "String.h" VS <string.h> | Friends
On HP-UX box when Iam passing a string object to function
Im getting the following below error
Error 422: "../header/Handler.h", line 24 # 'string' is used as a type, but has not been
defined as a type. Perhaps you meant 'String' as in class String
["/opt/aCC/include/SC/String.h", line 66].
int po... | Looks like there is a String class in the header mentioned by the compiler. The compiler thinks you made a typo.
If you want to use STL strings use the following:
#include <string>
int populateBindingHandle(rpc_if_handle_t p_if_spec, std::string ...)
or have a using declaration somewhere:
using std::string;
int popu... |
637,953 | 637,961 | g++ not working on Windows command prompt. Cygwin installed | I have installed Eclipse and CDT (to use C/C++ in eclipse CDT is needed), as well as installing Cygwin so that I can compile my files.
In environment variables I've set Path to include the following: "C:\cygwin\bin;"
g++, make and GDC are all installed via Cygwin. I made sure of this by searching for them in the bin fo... | I haven't used cygwin much, but my understanding is you have to use it from the cygwin bash shell.
if you need g++, make, etc, use mingw, with it, g++ works from the normal windows command line.
|
638,053 | 638,100 | How to Increment Visual Studio build number using C++? | I have a Visual Studio 2008 project that produces a file called: "Game-Release.exe".
This was configured under Project Properties -> C/C++ -> Linker -> General:
$(OutDir)\$(ProjectName)-Release.exe
I would like to take this a bit further by have an incrementing build number so I would have something which says:
Game-R... | The Versioning Controlled Build add-in seems like it would do the job.
Update: Your question specifically mentions using Visual Studio to increment the version, but there is nothing automated about that. Have you considered using Nant and a CI server? That way, it is easy to inject the SVN revision number into Assembly... |
638,090 | 638,139 | Profiling C++ multi-threaded applications | Have you used any profiling tool like Intel Vtune analyzer?
What are your recommendations for a C++ multi threaded application on Linux and windows? I am primarily interested in cache misses, memory usage, memory leaks and CPU usage.
I use valgrind (only on UNIX), but mainly for finding memory errors and leaks.
| Following are the good tools for multithreaded applications. You can try evaluation copy.
Runtime sanity check tool
Thread Checker -- Intel Thread checker / VTune, here
Memory consistency-check tools (memory usage, memory leaks)
- Memory Validator, here
Performance Analysis. (CPU usage)
- AQTime , here
EDI... |
638,101 | 638,122 | C/C++ Programming in Vista | I'm from a Java school, but I'd like to get my hands dirty in C/C++ development as well. Can you suggest:
a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download)
a full-blown advanced IDE [Eg: Eclipse for Java] (Every feature and huge download)
should I use GCC or other compilers?
Thanks a lot... |
1) a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download)
Eclipse with CDT (~40 MB download) or Visual Studio 2008 Express edition (2.6 MB download for installer and then tons of stuff that it'll pull from the net) -- it's free. Also, get the SP1. But, I still suggest that you take a look at ... |
638,251 | 638,693 | How to emit cross-thread signal in Qt? | Qt documentation states that signals and slots can be direct, queued and auto.
It also stated that if object that owns slot 'lives' in a thread different from object that owns signal, emitting such signal will be like posting message - signal emit will return instantly and slot method will be called in target thread's... | There are quite a few problems with your code :
like said by Evan the emit keyword is missing
all your objects live in the main thread, only the code in the run methods live in other threads, which means that the MySlot slot would be called in the main thread and I'm not sure that's what you want
your slot will never ... |
638,260 | 638,492 | Why does this take so long to compile in VCC 2003? | My team need the "Sobol quasi-random number generator" - a common RNG which is famous for good quality results and speed of operation. I found what looks like a simple C implementation on the web. At home I was able to compile it almost instantaneously using my Linux GCC compiler.
The following day I tried it at work:... | To be honest, I'm not really sure the codes that good. It's got a nasty smell in it. Namely, this function:
unsigned int i4_xor ( unsigned int i, unsigned int j )
//****************************************************************************80
//
// Purpose:
//
// I4_XOR calculates the exclusive OR of two integers... |
638,277 | 640,908 | Loading DLL from a location in memory | As the question says, I want to load a DLL from a location in memory instead of a file, similarly to LoadLibrary(Ex). I'm no expert in WinAPI, so googled a little and found this article together with MemoryModule library that pretty much meets my needs.
On the other hand the info there is quite old and the library hasn... | Well, you can create a RAM Drive according to these instructions, then copy the DLL you can in memory to a file there and the use LoadLibrary().
Of course this is not very practical if you plan to deploy this as some kind of product because people are going to notice a driver being installed, a reboot after the install... |
638,452 | 1,060,391 | Prolog ECLiPSe - how to implement yield method? | i'm using ECLiPSe programming logic system.
i want to implement the yield method for passing the values from prolog to C/C++.
Has anyone implemented it?
Are there any other ways for passing the values?
| The following page tells how to integrate ECLiPSe with C++ using the yield method:
http://87.230.22.228/doc/embedding/embroot006.html#toc8
|
638,704 | 643,766 | Why QWidget::paintEvent doesn't get called? | I have a simple hierarchy of widgets: GraphWidget -> MotionWidget -> NodeWidget. I am new to Qt, so I am not quite sure about how some insides work yet. Basically, GraphWidget creates a single MotionWidget M and sets M's parent to itself. M then goes away and creates a bunch of NodeWidgets. However, NodeWidgets never g... | I'm going to disagree with Aiua's answer. Passing the parent to an object will add the child to the visual hierarchy. (Otherwise, using Designer to make a widget including others, but with absolute positioning, wouldn't work.) However, there were probably other factors keeping the painting from happening.
Due to the... |
639,100 | 639,426 | Pointer to member functions - C++ std::list sort | How do i pass a pointer to a member function to std::list.sort()?
Is this possible? Thanks
struct Node {
uint32_t ID;
char * Value;
};
class myClass {
private:
uint32_t myValueLength;
public:
list<queueNode *> MyQueue;
bool compare(Node * first,... | Elaborating on grieve's response, why not use a functor? E.g.:
struct Functor
{
bool operator()( char * a, char * b )
{ return strcmp(a,b) < 0; }
};
Then you could just use:
Functor f;
myList.sort(f);
You could even use your class as the Functor by defining operator()...
class myClass {
...
bool operator()... |
639,194 | 639,291 | Linker issue: undefined reference | I have a problem with the linker when I build my current project.
The error it comes up with is as follows:
libmiinddynamic.so: undefined reference to `std::basic_ostream<char, std::char_traits<char> >& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::basic... | can you nm the object which is generated by above shown code, to see that the
signature is indeed what you expect.
|
639,248 | 639,276 | C++ covariant templates | I feel like this one has been asked before, but I'm unable to find it on SO, nor can I find anything useful on Google. Maybe "covariant" isn't the word I'm looking for, but this concept is very similar to covariant return types on functions, so I think it's probably correct. Here's what I want to do and it gives me a... | Both the copy constructor and the assignment operator should be able to take a SmartPtr of a different type and attempt to copy the pointer from one to the other. If the types aren't compatible, the compiler will complain, and if they are compatible, you've solved your problem. Something like this:
template<class Type>... |
639,496 | 639,662 | C++ comparing bunch of values with a given one | I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util function. Anyone wrote one?
Number of values I am comparing with is known at the compile time.
Update: I'd like to get rid of containers as I ... | For your request to do
if (InSet(value)(GetValue1(), GetValue2(), GetValue3()))
{
// Do something here...
}
Try this:
template <typename T>
class InSetHelper
{
const T &Value;
void operator=(const InSetHelper &);
public:
InSetHelper(const T &value) : Value(value) {}
template<class Other, class... |
639,676 | 639,702 | Overloading global operator new/delete in C++ | I am trying to overload the global operator new and delete for a performance sensitive application. I have read the concerns described at http://www.informit.com/articles/article.aspx?p=30642&seqNum=3 and the recommendations to use Intel TBB's allocator http://www.intel.com/technology/itj/2007/v11i4/5-foundations/5-mem... | If you want to overload the global operator new and operator delete, you just need to implement it. You don't need to explicitly define it everywhere since it already is defined as part of the language.
Edit: If you want to define an operator new that takes different parameters, then you'll need to #include it everywhe... |
639,922 | 640,499 | How do you usually return an instance of a user-defined type allocated on the local stack | I am curious about prevalent methodologies.
I found myself doing both of these things interchangeably:
Note in all cases the object is allocated locally.
std::string GetDescription ()
{
std::string desc;
/* Create a description */
return desc;
}
void GetResult (map<int, double> & resultMap)
{
... | It greatly depends on the task at hand. I would go for the first approach for functions that create new values while using the second approach for functions that change the parameters. As mentioned by others, in some cases other restrictions (cost of creation / assignment) can affect the decision.
The first definition ... |
639,952 | 642,351 | Linker problem, doesn't find an existing method? | Ok, I'm having issues with the linker on my current project (This is a continuation of another question, ish)
Basically, the linker gives an undefined reference in dynamiclib.so for:
std::basic_ostream<char, std::char_traits<char> >& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultP... | Ok, I managed to fix this this morning after about 10 hours hacking away last night.
Turns out that it compiles if you make the definitions of the function inline, and make sure it has options for the function with both all the template arguments and just non-defaulted arguments!
|
640,095 | 640,761 | When using a GL_RGBA16F_ARB-texture, it contains just crap, but I get no error message | I generate a texture like this:
GLuint id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParamet... | There shouldn't be anything special to do for setting up a framebuffer with float textures. Some things I would check:
Is the FBO bound and the draw/read buffer set correctly before you call glCheckFramebufferStatusEXT? Also try testing it right before you draw to it.
Does the texture look ok after a simple glClear wi... |
640,476 | 3,622,886 | Visual Studio 2005 Ignores Preprocessor directives during compile | We just got a new developer and I'm trying to set him up with Dev Studio 2005 (The version we all use at this office), and we're running into a weird problem that I've never seen before.
I have some code that works perfectly on my system, and he can't seem to get it compiled. We've tracked the issue down to his copy... | I recently ran into the same symptom with VS2005. Ultimately I was able to resolve it by explicitly adding my preprocessor defines via the Command Line - Additional options dialog:
Configuration Properties -> C/C++ -> Command Line
When I added '/DPROPERTY' there it was recognized at compile time, whereas adding it u... |
640,518 | 640,529 | Easiest way to repeat a sequence of bytes into a larger buffer in C++ | Given (in C++)
char * byte_sequence;
size_t byte_sequence_length;
char * buffer;
size_t N;
Assuming byte_sequence and byte_sequence_length are initialized to some arbitrary length sequence of bytes (and its length), and buffer is initialized to point to N * byte_sequence_length bytes, what would be the easiest way to ... | I would probably just go with this:
for (int i=0; i < N; ++i)
memcpy(buffer + i * byte_sequence_length, byte_sequence, byte_sequence_length);
This assumes you are dealing with binary data and are keeping track of the length, not using '\0' termination.
If you want these to be c-strings you'll have to allocate an e... |
640,657 | 640,678 | What's the difference between C and C++ | I know that C++ has the concept of objects but C doesn't. I also know that pretty much all there is to know about C fits into K & R but the C++ library is vastly more complex. There have got to be other big differences though.
What are the major differences between C and C++?
| Check out Stroustrup's FAQ here, specifically:
What is the difference between C and C++?
C++ is a direct descendant of C that
retains almost all of C as a subset.
C++ provides stronger type checking
than C and directly supports a wider
range of programming styles than C.
C++ is "a better C" in the sense that... |
640,721 | 640,740 | Most used STL algorithm, predicates, iterators | I cannot find this question on stackoverflow. But I am wondering how people use STL (No fancy boost)... just an ol' fashion STL. Tricks/tips/mostly used cases acquired over many, many years... and perhaps gotchas...
Let's share it...
One tip per answer...with code example --
Edit is it such a bad question as it result... | I use the STL in almost all of my projects, for things from loops (with iterators) to splitting up the input into a program.
Tokenise an input string by spaces and input the result into an std::vector for parsing later:
std::stringstream iss(input);
std::vector<std::string> * _input = new std::vector<std::string>();
s... |
640,731 | 640,842 | Quick way to fill vector, map, and set, using stl functions | I want to fill these containers pretty quickly with some data for testing. What are the best and quick ways to do that? It shouldn't be too convoluted, and thus and inhumanly short, but also NOT to verbose
Edit
Guys I thought you can do something with memset knowning that vector has an underlining array?
Also, what ab... | If you already have the initial data laying around, say in a C style array, don't forget that these STL containers have "2-iterator constructors".
const char raw_data[100] = { ... };
std::vector<char> v(raw_data, raw_data + 100);
Edit: I was asked to show an example for a map. It isn't often you have an array of pair... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.