question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,377,685 | 1,377,707 | virtual method not seen in implementation | i am currently working on a C++ project where i have an abstract interface that is implemented later on. The interface also has a implemented method which my implementation doesn't override.
My problem is that when using my implementation, the compiler(MSVC) doesn't see the interface method. What causes this, and how can i resolve it?
Here comes the code.
#include <string>
#include <vector>
using std::string;
class A
{
public:
string name;
};
class interface
{
public:
virtual int num_foo() = 0;
virtual A* foo(int) = 0;
virtual A* foo(string &name){
for ( int i(0); i < num_foo(); i++)
if ( foo(i)->name == name )
return foo(i);
return 0;
}
};
class implementation : public interface
{
public:
virtual int num_foo() { return m_foos.size(); }
virtual A* foo(int i) {
//check range
return &m_foos[i];
}
std::vector<A> m_foos;
};
int main(...)
{
implementation impl;
// impl is properly initialized here
string name( "bar" );
// here comes my problem, the MSVC compiler doesn't see foo(string &name)
// and gives an error
A *a = impl.foo( name );
}
| Name resolution happens before overload resolution. In impl.foo( name ), then compiler looks at the implementation class and finds only virtual A& foo(int i). It does not look at the base class as it has found a function with the right name.
To correct this use can add a using interface::foo declaration to the derived class to pull all of the base versions of foo into the derived class for the purposes of overload resolution. Usually, I'd prefer to avoid overloaded functions and I'd probably give the variants of foo different function names.
(Other errors are that you don't define string, vector or m_ones; you attempt to use -> instead of . on a reference and you attempt to return 0 in a function returning a reference to an A.)
|
1,377,695 | 1,377,865 | Is there a reason to use enum to define a single constant in C++ code? | The typical way to define an integer constant to use inside a function is:
const int NumbeOfElements = 10;
the same for using within a class:
class Class {
...
static const int NumberOfElements = 10;
};
It can then be used as a fixed-size array bound which means it is known at compile time.
Long ago compilers didn't support the latter syntax and that's why enums were used:
enum NumberOfElementsEnum { NumberOfElements = 10; }
Now with almost every widely used compiler supporting both the in-function const int and the in-class static const int syntax is there any reason to use the enum for this purpose?
| The reason is mainly brevity. First of all, an enum can be anonymous:
class foo {
enum { bar = 1 };
};
This effectively introduces bar as an integral constant. Note that the above is shorter than static const int.
Also, no-one could possibly write &bar if it's an enum member. If you do this:
class foo {
static const int bar = 1;
}
and then the client of your class does this:
printf("%p", &foo::bar);
then he will get a compile-time linker error that foo::bar is not defined (because, well, as an lvalue, it's not). In practice, with the Standard as it currently stands, anywhere bar is used where an integral constant expression is not required (i.e. where it is merely allowed), it requires an out-of-class definition of foo::bar. The places where such an expression is required are: enum initializers, case labels, array size in types (excepting new[]), and template arguments of integral types. Thus, using bar anywhere else technically requires a definition. See C++ Core Language Active Issue 712 for more info - there are no proposed resolutions as of yet.
In practice, most compilers these days are more lenient about this, and will let you get away with most "common sense" uses of static const int variables without requiring a definition. However, the corner cases may differ, however, so many consider it to be better to just use anonymous enum, for which everything is crystal clear, and there's no ambiguity at all.
|
1,377,813 | 1,379,097 | QT: reject() closing whole app? Why? | I'm running a QT app (VS2005) and have spawned a dialog from that app, but if I add a cancel button to that dialog with a reject() slot then yes, the dialog closes and returns the correct result but my whole app closes down as well.
This is annoying me and I can't find any hint as to why; any suggestions gratefully recieved
| Perhaps look at setting this:
http://doc.trolltech.com/4.5/qapplication.html#quitOnLastWindowClosed-prop
to false?
If that doesn't work, make sure you haven't got any signal / slot connections you may have forgotten about.
|
1,377,833 | 1,392,505 | Unable to catch std::invalid_argument | I've run into an issue catching a std::invalid_argument exception that I'm not able to trace. I'm using gcc 4.4.0 (windows), pthreads-win32 2.8.0 the GC2 dll.
Basically, from two threads (main thread and a thread started using pthread_create), I try to create an instance of class A at roughly the same time. The constructor throws an std::invalid_argument, but it is surrounded by try/catch blocks which should catch the exception. However, that does not happen (very rarely, only one of the threads might catch the exception - no rule as to which will do it though)
If I attempt to create the object on only one of the threads, the create works as it should, and the exception is caught. If I create the two objects at different times, the create works as it should and the exception is caught. If I try to create them at the same time, ::terminate() gets called.
Maybe someone has an idea of why this happens (I've excluded headers):
void *run(void *ptr)
{
Sleep(5000);
try
{
A *a = new A(5);
a->a = 12;
}
catch (std::exception &ex)
{
printf("t - %s\n", ex.what());
}
return NULL;
}
int main(void) {
pthread_t t;
if (pthread_create(&t, NULL, run, NULL) != 0)
{
printf("No thread\n");
}
else
{
Sleep(5000);
try
{
A *a = new A(5);
a->a = 13;
} catch (std::exception &ex)
{
printf("M - %s\n", ex.what());
}
pthread_join(t, NULL);
}
return 0;
}
class A
{
public:
A(int a);
virtual ~A();
int a;
};
A::A(int a)
{
throw std::invalid_argument("Invalid!");
}
A::~A(){}
The makefile is:
CXXFLAGS = -O0 -g -Wall -Werror -fmessage-length=0
OBJS = WOpenTest.o A.o
INCL = -I../pthreads-win32/include
LIBS = -lws2_32 -lgdi32 -lpthreadGC2
LIB_DIRS = -L ../pthreads-win32/lib
TARGET = WOpenTest.exe
$(TARGET): $(OBJS)
$(CXX) -o $(TARGET) $(OBJS) $(LIBS) $(LIB_DIRS) $(INCL)
WOpenTest.o : WOpenTest.cpp
g++ $(CXXFLAGS) -c WOpenTest.cpp $(INCL)
A.o : A.cpp A.h
g++ $(CXXFLAGS) -c A.cpp $(INCL)
all: $(TARGET)
clean:
rm -f $(OBJS) $(TARGET)
The output I am seeing is:
(Most frequently) $ ./WOpenTest.exe
This application has requested the
Runtime to terminate it in an unusual
way. Please contact the application's
support team for more information.
This application has requested the
Runtime to terminate it in an unusual
way. Please contact the application's
support team for more information.
terminate called after throwing an
instance of 'std::invalid_argument'
terminate called recursively
or
$ ./WOpenTest.exe
This application has requested the
Runtime to terminate it in an unusual
way. Please contact the application's
support team for more information.
M - Invalid!
or
$ ./WOpenTest.exe
This application has requested the
Runtime to terminate it in an unusual
way. Please contact the application's
support team for more information.
t - Invalid!
or
This application has requested the
Runtime to terminate it in an unusual
way. Please contact the application's
support team for more information.
This application has requested the
Runtime to terminate it in an unusual
way. Please contact the application's
support team for more information.
terminate called after throwing an
instance of 'std::invalid_argument'
what(): Invalid!
Any ideas on what I should be doing and I'm not? Or something I'm missing with pthreads?
| Posting final answer here in case someone looks for it in the future. The issue is a critical bug in gcc 4.4:
http://n2.nabble.com/gcc-4-4-multi-threaded-exception-handling-thread-specifier-not-working-td3440749.html
|
1,377,843 | 1,386,069 | Cannot get ::WideCharToMultiByte to work | I've got a DLL for injection. This is injected via CBT-hook. Now, when the desired
process is encountered via CBT, I've detoured WinAPI's ExtTextOutW with my own. The specification of ExtTextOutW is:
BOOL ExtTextOutW(HDC hdc,
INT x,
INT y,
UINT flags,
const RECT* lprect,
LPCWSTR str,
UINT count,
const INT* lpDx)
In my detoured ExtTextOutW i'm trying to convert str (LPCWSTR) to multibyte with the following code:
BOOL Mine_ExtTextOutW(HDC hdc,
INT x,
INT y,
UINT flags,
const RECT* lprect,
LPCWSTR str,
UINT count,
const INT* lpDx)
{
BOOL rv = Real_ExtTextOutW(hdc, x, y, flags, lprect, str, count, lpDx);
HANDLE h = ::WindowFromDC(hdc);
if (!h || !str)
return ev;
CHAR *buffer = (CHAR *)::LocalAlloc(count + 1);
int l = ::WideCharToMultiByte(CP_APC, 0, str, count, buffer, count, NULL, NULL);
if (l > -1) {
buffer[l] = '\0';
g_pClient->SendViaIPC(buffer);
}
::LocalFree(buffer);
return rv;
}
Unfortunately, this doesn't work. WideCharToMultiByte hangs the injected process. Why?
| Your code looks a little odd, does it compile?
LocalAlloc should have two parameters and did you mean CP_ACP. Anyway instead I would:
Ask WideCharToMultiByte for the correct size, just in case you change your code page in future.
Check for > 0 (failure is represented by 0 and not -1)
Use std strings just to make sure you don't have any memory leaks, exceptions etc.
So something like this:
int nMultiByteSize = ::WideCharToMultiByte( CP_ACP, NULL, str, count, NULL, 0, NULL, NULL );
if ( nMultiByteSize > 0 )
{
std:string strMulti;
strMulti.resize( nMultiByteSize );
if ( ::WideCharToMultiByte( CP_ACP, NULL, str, count, &strMulti[0], (int)strMulti.size(), NULL, NULL ) > 0)
{
g_pClient->SendViaIPC(strMulti.c_str());
}
}
|
1,377,852 | 1,377,911 | Accessing functions in an ASM file from a C++ program? | Over here I asked about translating an ASM file to C, and from the responses it looked like there was no reasonable way to do it. Fine. So one of the responses suggested I just make use of the functions as-is and be done with it. Sounds good.
But how?
Holy crap I've tried everything I can think of! I'm using a Microchip brand MCU (PIC18F4480) and a Microchip brand IDE (MPLAB IDE) and the ASM files are Microchip authored... so you'd think I'd find some way of making use of them! So far no luck at all.
I don't know anything about ASM (Assembly). I code in C++ and frankly that's not going to change. There has got to be a way to access the functions in the Microchip ASM files without rewriting all my code in a new language.
If anyone wants to take a look, the ASM files and application notes are here.
| Looking at PIDInt.asm, it should be fairly straight-forward to call the functions from C/C++.
First, you declare extern variables for everything listed in VARIABLE DEFINITIONS:
extern unsigned char error0, error1; /* etc */
Then, you declare extern functions for all the things that have a "Function:" comment, taking no arguments and returning no result:
extern void Proportional(); // extern "C" for C++
To call one of them, you fill the input variables, call the function, and read the output variables.
|
1,377,873 | 1,377,909 | Eclipse CDT: Shortcut to switch between .h and .cpp? | In Eclipse, is there a keyboard shortcut for switching the editor view from viewing a .cpp file to a corresponding .h file, and vice versa?
| Ctrl+Tab is the default shortcut.
You can change it in Window → Preferences → General → Keys: Toggle Source/Header
|
1,377,912 | 1,377,968 | Conflict between a namespace and a define | I have this serious problem. I have an enumeration within 2 namespaces like this:
namespace FANLib {
namespace ERROR {
enum TYPE {
/// FSL error codes
FSL_PARSER_FILE_IERROR,...
and somewhere else in my code, I use it like this:
FANLib::Log::internalLog(FSLParser::FILE_IERROR, file_ierror, true, FANLib::ERROR::FSL_PARSER_FILE_IERROR);
All compiles fine and well, but if I happen to include "windows.h", I get errors! The problem is in "WinGDI.h" which has this line:
#define ERROR 0
and makes the compiler think that, after FANLib::..., there is a zero!
The error I get is :
Error 1 error C2589: 'constant' : illegal token on right side of '::'
Error 2 error C2059: syntax error : '::'
Error 3 error C2039: 'FSL_PARSER_FILE_IERROR' : is not a member of '`global namespace''
Is there anything I can do about this, without having to change my namespaces due to some thoughtless #define? I have read in another post that I could #undef ERROR, but how safe is that?
| Generally, you should avoid using all-caps identifiers as they are used for macros. In this case, I'd rename the namespace.
(As a side note, <windows.h> #defines other stuff like GetPrinter and indeed it gets annoying. I usually go with #undef then. It also helps to only include <windows.h> in .cpp files and make sure the scope affected by the header is as small as possible.)
|
1,378,136 | 1,378,152 | Ensuring correct Double Pointer passing method at compile-time in C++ | in the past we encountered various memory-leaks in our software. We found out that these happened mostly due to incorrect usage of our own "free"-Methods, which free Queue-Message-Data and the likes.
The problem is, in our deepest tool-functions there are two methods to free up dynamically allocated memory, with the following signatures:
void free (void *pData);
void free (void **ppData);
Both methods basically do the same thing, except the second one dereferences the data first. I know that it is possible to do everything with just one of these two, but lets just say that the software was designed that way many years ago and now theres code everywhere using both.
The problem comes in, when somebody implements a call to these methods like this:
QueueMessage *pMsg;
pMsg = myQueue.read(...); // dynamically allocates space for the msg and fills it
// Do something
myQueue.free(&pMsg); // << WRONG!
The code above should pass the pointer to the message to the free-method. Basically it would work, but since the compiler doesn't know which function to use in this case, it uses the free(void *pData) method which then tries to free the Pointer, not the memory which the Pointer points to. Of course, the solution is easy, either:
myQueue.free(pMsg);
or
myQueue.free((void**)&pMsg);
Both will work. Now that I've described the problem and the solution, I'd like to know: Is there any way I can ensure that the programmer using these methods uses them the right way? I've read about header annotations in VS2005, which are quite useful, but don't seem to do what I need. It would be great if there is a way to produce a warning if the reference of a pointer is passed to the first method, so the programmer at least gets a hint that there's something wrong with his code.
By the way, I'm using Microsoft VS2005 and have the possibility to upgrade to VS2008 if needed. It's a C++ Application migrated to VS2005, and therefore .NET-compatible.
| Try templates:
template <class T> void free (T *pData);
template <class T> void free (T **ppData);
This should give you an exact match on the argument type and, hence, the compiler should call the correct implementation.
You can either replace your original void-pointer implementations of free with the templated versions, or have the templated versions call the original void-pointer versions:
template <class T> void free (T *pData)
{
free(static_cast<void *>(pData));
}
template <class T> void free (T **ppData)
{
free(static_cast<void **>(ppData));
}
Edit: So what was going on in the original version?
The rules for overloaded function resolution are fairly complicated, but in principle, the compiler first tries to find an exact math for the argument types and, if it can't find them, there is a variety of automatic type conversions it can apply.
One of these automatic type conversions is that any pointer -- including a pointer-to-pointer -- can be converted to a void * pointer. There is, however, no rule that a typed pointer-to-pointer (T **) can be converted automatically to a void pointer-to-pointer (void **). This is why all of your calls were going to free(void *).
When you introduce the templated versions, this changes. The compiler can now find an exact match for every call that you make -- either free(T *) or free(T **) -- and this enables it to call the correct version.
|
1,378,165 | 1,378,416 | A good way to implement useable Callbacks in C++ | I have a custom Menu class written in C++. To seperate the code into easy-to-read functions I am using Callbacks.
Since I don't want to use Singletons for the Host of the Menu I provide another parameter (target) which will be given to the callback as the first parameter (some kind of workaround for the missing "this" reference).
Registration-Signature
AddItem(string s, void(*callback)(void*,MenuItem*), void* target = NULL)
Example of a Registration
menu->AddItem(TRANSLATE, "translate", &MyApp::OnModeSelected);
Example of a Handler
/* static */
void MyApp::OnModeSelected(void* that, MenuItem* item) {
MyApp *self = (MyApp*)that;
self->activeMode = item->text;
}
Is there anything one could consider dirty with this approach? Are there maybe better ones?
| Your approach requires the callback functions to either be free functions or static members of a class. It does not allow clients to use member functions as callbacks. One solution to this is to use boost::function as the type of the callback:
typedef boost::function<void (MenuItem*)> callback_type;
AddItem(const std::string& s, const callback_type& callback = callback_type());
Clients can then use boost::bind or boost::lambda to pass in the callback:
menu->AddItem("Open", boost::bind(&MyClass::Open, this));
Another option is to use boost::signals which allows multiple callbacks to register for the same event.
|
1,378,197 | 1,378,256 | How to write strings as binaries to file? | This is a C++ question. I have a class that contains a string:
class MyClass{
public:
std::string s;
};
And I have an array of MyClass objects:
MyClass * array = MyClass[3];
Now I want to write the array as binaries into a file. I cannot use:
Ofstream.write((char *)array, 3 * sizeof(MyClass))
because the size of MyClass varies.
How can I use Ofstream.write to achieve the purpose? Many thanks.
| In C++ it is usually done using the BOOST serialization class
Programmatically you could do something like this:
Writing:
std::ofstream ostream("myclass.bin",std::ios::binary);
if (!ostream) return; // error!
std::size_t array_size = 3;
ostream.write(reinterpret_cast<char*>(&array_size),sizeof(std::size_t));
for(MyClass* it = array; it != array + array_size; ++it)
{
MyClass& mc = *it;
std::size_t s = mc.s.size();
ostream.write(reinterpret_cast<char*>(&s),sizeof(std::size_t));
ostream.write(mc.s.c_str(),s.size());
}
Reading
std::ifstream istream("myclass.bin",std::ios::binary);
if (!istream) return; // error!
std::size_t array_size = 0;
istream.read(reinterpret_cast<char*>(&array_size),sizeof(std::size_t));
array = new MyClass[array_size];
for(MyClass* it = array; it != array + array_size; ++it)
{
MyClass& mc = *it;
std::size_t s;
istream.read(reinterpret_cast<char*>(&s),sizeof(std::size_t));
mc.resize(s);
istream.read(mc.s.c_str(),s.size());
}
istream.close(); // not needed as should close magically due to scope
|
1,378,250 | 1,379,739 | What error codes can occur with CopyFileEx? | I'm writing some C++ code that needs to call the CopyFileEx function. The documentation for CopyFileEx, like most other WIN32 functions, says:
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Which is all well and good - however does anyone know where I can find a list of the error codes that a specific API function may return via GetLastError? In this case I want to handle different error conditions in different ways but without a list of the error codes for this function I'm going to be reduced to generating the error conditions I want to handle just to see what error code is prodcued or going through the system error codes from numbers 0 to 15999 trying to guess which ones might apply!
Edit: Here is a little more context to help explain the issue and why I want to know if there is a definitive list of error codes that can be returned by a function anywhere.
The code will be used as part of a Windows service so while there are users they won't always be there to respond to errors. I need to be able to distinguish between errors that don't need reporting every time, if a file is locked I'm just to re-try it again later. If I don't have permissions to read a particular file I can log the problem and carry on, if the destination directory is unreadable or is full then I want the service to stop and to trigger a reporting process that will atrract the attention of a user.
Without a comprehensive list of the ways that CopyFileEx can fail I'm finding it hard to do this.
| Microsoft doesn't give a list of all error codes an API might return for the simple reason that the list may change over time and various implementations of Windows, installed drivers or simple oversight (APIs often return errors caused by other APIs called within the one you called).
Sometimes the docs call out specific errors that are of particular interest for users of that API, but in general they will not has a definitive complete list of errors. Nor should they, which is unfortunate, but is a fact of life.
I sympathize with your plight - there are many times I would have liked this kind of information so I could have a better idea of how to handle problems that should be anticipated - particularly those that have a reasonable recovery path. Usually I try to deal with this by testing to find the failure behavior of the APIs, and I'd like to avoid that because it's a pain and it doesn't help much with ensuring that I've covered all the scenarios or against future differences.
However, covering all the scenarios (with a comprehensive list of error codes) or protecting against future changes is really an impossible goal. Consider how Microsoft might have to manage documenting all possble error codes in Win32:
Say the Win32 API has only 2 functions: foo() and bar(). foo() might generate its own error, ERROR_FOO and bar() might generate its own error, ERROR_BAR. However, foo() calls bar(), so foo() might also return ERROR_BAR if its call to bar() returns that error.
The docs reflect the following:
foo() may retun either ERROR_FOO or ERROR_BAR
bar() may return ERROR_BAR
Now, when API v2 is released, bar() has been extended to also return ERROR_BAZ. for something the size of this API it's simple to manage that the docs for bar() need to be updated to add the new error code (however, note that for an API as large as the real Win32 and an organization as large as MS, the same might not be true, but lets assume it is).
However, the guy adding the new error to bar() has no direct visibility to the fact the foo()'s behavior has also changed in terms of what errors it might return. In an API small as this, it's probably not a big deal - in something like Win32 it would be a mess. Now throw in the fact that Win32 can be dependant on 3rd party code (drivers, plug-ins, COM objects, etc) and the task is now pretty near impossible.
Actually that's not necessarily a great example, since if the error codes were part of the contract of an API ERROR_BAZ should have never come into the picture.
So here's another scenario: the API has an OpenObject() function that can return ERROR_NO_MEMORY or ERROR_NOT_FOUND. When this system was first developed, it had no concept of security (say like MS-DOS), but a new release adds access controls. Now we'd like OpenObject() to be able to return ERROR_ACCESS_DENIED, but it can't because that would change the contract, so a new API OpenObjectEx() is added to deal with that situation. There are at least 2 problems here:
You'll get an explosion of APIs over time that really add little or no value over the old APIs
what should happen to a legacy application that calls the old OpenObject() API and fails because of access restrictions? Neither of the contracted error returns would tell the truth about what the problem is.
This problem is one of the reasons that exception specifications (in C++ or Java) are considered by many to have been a bad idea.
|
1,378,364 | 1,378,428 | How do you output variable's declared as a double to a text file in C++ | I am very new to C++ and I am wondering how you output/write variables declared as double to a txt file. I know about how to output strings using fstream but I cant figure out how to send anything else. I am starting to think that you can't send anything but strings to a text file is that correct? If so then how would you convert the information stored in the variable to a string variable?
Here is my code that I'm trying to implement this concept into, Its fairly simple:
int main()
{
double invoiceAmt = 3800.00;
double apr = 18.5; //percentage
//compute cash discount
double discountRate = 3.0; //percentage
double discountAmt;
discountAmt = invoiceAmt * discountRate/100;
//compute amount due in 10 days
double amtDueIn10;
amtDueIn10 = invoiceAmt - discountAmt;
//Compute Interest on the loan of amount (with discount)for 20 days
double LoanInt;
LoanInt = amtDueIn10 * (apr /360/100) * 20;
//Compute amount due in 20 days at 18.5%.
double amtDueIn20;
amtDueIn20 = invoiceAmt * (1 + (apr /360/100) * 20);
return 0;
}
So what I'm trying to do is use those variables and output them to the text file. Also please inform me on the includes that I need to use for this source code. Feel free to give suggestions on how to improve my code in other ways as well please.
Thanks in advance.
| As your tagging suggests, you use file streams:
std::ofstream ofs("/path/to/file.txt");
ofs << amtDueIn20;
Depending on what you need the file for, you'll probably have to write more stuff (like whitespaces etc.) in order to get decent formatting.
Edit due to rmagoteaux22's ongoing problems:
This code
#include <iostream>
#include <fstream>
const double d = 3.1415926;
int main(){
std::ofstream ofs("test.txt");
if( !ofs.good() ) {
std::cerr << "Couldn't open text file!\n";
return 1;
}
ofs << d << '\n';
return 0;
}
compiles for me (VC9) and writes this to test.txt:
3.14159
Can you try this?
|
1,378,520 | 1,378,682 | Elevated process in Vista does not overwrite files | I'm trying to run elevated process, say, file_copier.exe, from another host process with ShellExecuteEx and lpVerb = "runas" on Vista. It shows UAC dialog and runs elevated, and copies files to "dangerous" folders, but it does not overwrite existing files (exe's).
I've read here: http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx that UAC does not actually overwrite existing files but stores new files in a cache of some sort. But I can't figure out (if it is the case), how to make it actually overwrite existing files. Any help is appreciated.
| You are talking about virtualization of file system. To tell Windows that your program are aware of Windows rules you should change your manifest file.
Add to the manifest the following text:
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!--The ID below indicates application support for Windows Vista -->
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
<!--The ID below indicates application support for Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
<!--The ID below indicates application support for Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
</application>
</compatibility>
|
1,378,588 | 1,378,625 | How can I use Enum::GetName in unmanaged C++ | I am using managed extensions in VS 2008
I want to print the name of an en enum value
This code used to be fine VS 2003
Enum::GetName(__typeof(COMMAND_CODES),__box(iTmp))
but now I get a comile error
here is my enum
typedef enum { /* Command codes */
UMPC_NULL = 0,
} COMMAND_CODES
Any clues ?
;
| Can you use rtti typeid() and use the name() field?
Edit: From comment:
Enum::GetName(COMMAND_CODES::typeid,iTmp)
|
1,378,735 | 1,378,807 | Problem with file stream/fstream in Xcode C++ | Here is a simple program to output to a text file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double myNumber = 42.5;
fstream outfile("test.txt", fstream::out);
outfile << "The answer is almost " << myNumber << endl;
outfile.close();
}
All that ends up being wrote to my text file is, "The answer is almost " and the data is not displayed at all. What am I doing wrong? or could it be a problem with Xcode since I am using that as an IDE.
| I'm not sure what the problem is. Is it that it's never executed or that it's writing to the wrong path. To shed light on this try include unistd.h and insert this snippet.
char* s = getcwd(NULL, 256);
printf("im running and pwd is: %s\n", s);
Inside xcode hit CMD-SHIFT-R to open the console and see if it prints anything.
|
1,378,867 | 1,379,311 | Using find_if on std::vector<std::string> with bind2nd and string::compare | This may seem to be an academic question, but still I would be very interested in the answer:
I have a vector of strings s in which I would like to find a given string findme. This can be done using something like
find(s.begin(), s.end(), findme);
My question is: There must be a way doing the same using find_if and the compare method of the STL strings as predicate, but how? Something like
find_if(s.begin(), s.end(), bind2nd(mem_fun_ref(&string::compare), string("findme")) );
does not work, because the compare method has several overloads and the compiler does not know which one to choose.
As a second step: My motivation for using find_if instead of find is that I have a vector of objects derived from a class having a string property name and I want to find an object with a given name. Is this possible (without writing an extra function to be used as predicate)?
EDIT: As some (most :) answers mentioned using Boost -- I would prefer not to have to include Boost for this. (As far as I know, most of the Boost libraries are "only" templates, so there should be a way without using Boost.)
| One option is to cast the member function pointer to suitable type. Another thing you are forgetting is that std::string::compare returns 0 for equal strings, so you'll also need to negate the functor. All in all:
std::find_if(
vec.begin(), vec.end(),
std::not1(
std::bind2nd(
std::mem_fun_ref(static_cast<int (std::string::*)(const char*)const>(&std::string::compare)),
"findme"
)
)
);
As to your rationale against boost: its templates are an order of a magnitude more flexible than what you can find in STL functional header. It's either boost, you wait for C++0x lambdas (which I believe will be the preferable way in such situations) or you write some helpers yourself. Currently it can't get simpler than:
std::find_if(vec.begin(), vec.end(), boost::bind(&X::name, _1) == "findme");
FYI, C++0x will add std::bind which is similar to boost::bind but it seems the convenience of overloaded operator== will not be there.
|
1,379,246 | 1,379,261 | Any reason to replace while(condition) with for(;condition;) in C++? | Looks like
while( condition ) {
//do stuff
}
is completely equivalent to
for( ; condition; ) {
//do stuff
}
Is there any reason to use the latter instead of the former?
| There's no good reason as far as I know. You're intentionally misleading people by using a for-loop that doesn't increment anything.
Update:
Based on the OP's comment to the question, I can speculate on how you might see such a construct in real code. I've seen (and used) this before:
lots::of::namespaces::container::iterator iter = foo.begin();
for (; iter != foo.end(); ++iter)
{
// do stuff
}
But that's as far as I'll go with leaving things out of a for-loop. Perhaps your project had a loop that looked like that at one time. If you add code that removes elements of a container in the middle of the loop, you likely have to control carefully how iter is incremented. That could lead to code that looks like this:
for (; iter != foo.end(); )
{
// do stuff
if (condition)
{
iter = foo.erase(iter);
}
else
{
++iter;
}
}
However, that's no excuse for not taking the five seconds needed to change it into a while-loop.
|
1,379,533 | 1,379,541 | How can I see symbols of (C and C++) binary on linux? | Which tools do you guys use? How do demangle c++ symbols do be able to pass it to profiler tools, such as opannotate?
Thanks
| Use nm to see all symbols and c++filt to demangle.
Example:
nm -an foo | c++filt
|
1,379,542 | 1,379,716 | Qt-GUI with several "pages", how to synchronize the size of several QWidgets | I am currently writing a wizard-style application using Qt4. I am not using the wizard class however, since going next/back does not make sense from every step in the process.
The user starts off at a "hub"-window with five buttons, each of which take him to another window at a different stage of the process. At the beginning all but the first button of the hub are disabled. After clearing each stage, the user will be directed back to the hub and one new button/stage will get enabled.
Since every stage has significantly differing objectives, I coded every single stage as a single QWidget that gets instantiated in the main() function. To switch between the widgets, I simply hide() the one I am leaving and show() the one I am going to.
However, this leads to problems if the user resized or moved one widget, since the next widget will always show up at its default position instead of the new one.
Is there a way to synchronize the widgets' sizes and positions?
Or, better yet, is there a more elegant way to deal with those different windows than switching between several hidden widgets?
Thank you in advance!
| Create one top-level widget that holds the others.
I suggest that you either use QStackedWidget, or, if you want more control, create your own widget and use QStackedLayout directly.
|
1,379,564 | 1,380,733 | C++: tiny memory leak with std::map | I am writing a custom textfile-data parser (JSON-like) and I have lost many hours trying to find a tiny memory leak in it.
I am using VC++2008 and the commands _CrtMemCheckpoint and _CrtDumpMemoryLeaks to check for memory leaks.
When I parse any file and then remove it from memory (alongside any other memory claimed), I get a 16 bytes memory leak which looks like this :
{290} normal block at 0x00486AF0, 16 bytes long.
Data: < H `aH hH eH > C0 9A 48 00 60 61 48 00 18 68 48 00 D8 65 48 00
I have managed to narrow the "offending" line of code down to this :
classDefinitions[FastStr(cString)] = classDef;
classDefinitions is an std::map<FastStr, FSLClassDefinition*> and is a private member of my parser class.
FastStr is a simple char* "wrapper" for allowing simple c-strings as key values; it has no memory leaks (no 'new' commands). 'FSLClassDefinition*' is obviously a simple class pointer, so nothing strange there either.
Now here is the catch :
this line is executed many times during the parse-process, but I only get a single 16-bytes block leaked.
if I parse another file, there is not another 16-bytes memory leak
If I remove the parser from memory (by having it in a {} code-block), then recreate it in another code-block and have it parse another file, then I get a second 16-bytes memory leak.
This leads me to suspect that there is a memory leak in std::map; but it could also be my mistake... I am pretty sure that's the offending line because if I stop the parsing before it, there is no memory leak; there is memory leak if I stop the parsing just after this line.
Can anyone comment on this?
| The "{290}" in the leak report is the sequence number of the memory allocation for the memory block that was leaked. If this sequence number is always the same, you can use _crtBreakAlloc to cause a break in the debugger when that allocation sequence number is hit. From the stack trace you can find out where this block is being allocated. Once you know where, and for what purpose, it is being allocated it tends to be fairly easy to determine why it is not being deallocated.
Read the Debug Heap documentation to learn about _crtBreakAlloc.
|
1,379,735 | 1,379,778 | visual studio - run several applications at once | The project, I work on, consists of several executables which run in background and a frontend. I develop in Visual Studio 2005. Often I need to run one background app with breakpoints enabled and then control it from the frontend. I set the important background app as a startup project and press F5. Then I start the frontend and the other background apps by "Start new Instance". A lot of clicking.
Is there a better way?
| Visual Studio lets you start multiple projects when you hit F5. See How to: Set Multiple Startup Projects
In a nutshell:
In Solution Explorer, select the solution.
On the Project menu, click Properties. The Solution Property Pages Dialog Box opens.
Expand the Common Properties node, and click Startup Project.
Click Multiple Startup Projects and set the project actions.
|
1,379,770 | 1,416,170 | How can I use std::for_each with boost::bimap? | I have a boost::bimap and I want to iterate over all positions
to add the values of the given side to another STL-compatible container.
How can I do this?
My approach was to use std::for_each together with boost::bind:
std::for_each(mybimap.left.begin(),
mybimap.left.end(),
boost::bind(&vector::push_back, &myvec,
boost::bind( ... )));
| This should work:
std::for_each(mybimap.left.begin(),
mybimap.left.end(),
boost::bind(&vector_type::push_back, &myvec,
boost::bind(&map_type::left_map::value_type::second, _1)));
... or if you mean the key values mapped from instead of the values being mapped to, use first instead of second.
EDIT: I find this double-bind rather clumsy, and the for_each a non-optimal algorithm (copy would be better suited, IMHO the algorithm name should state the intent and that's clearly a copy here). You could also use a transform iterator here:
std::copy(boost::make_transform_iterator(mybimap.left.begin(), select_second()),
boost::make_transform_iterator(mybimap.left.end(), select_second()),
std::back_inserter(myvec));
where select_second would be a function object that selects the second element of a pair - or just the boost::bind(&map_type::left_map::value_type::second, _1).
For a situation where I couldn't use a transform_iterator I have written a transform_back_inserter at work which is basically a back_inserter that takes an unary function that is applied to the element before writing (no rocket science to write) - then it would look like
std::copy(mybimap.left.begin(),
mybimap.left.end(),
transform_back_inserter(myvec, select_second()));
which I tend to prefer to the transform_iterator when possible as I don't have to repeat the unary function name.
|
1,379,932 | 1,380,025 | trick question regarding declaration syntax in C++ | Have a look here:
In the following code, what would be the type of b?
struct A {
A (int i) {}
};
struct B {
B (A a) {}
};
int main () {
int i = 1;
B b(A(i)); // what would be the type of b
return 0;
}
I'll appreciate it if anybody could explain to me thoroughly why would such syntax exist :)
Thanks.
| One of C's warts (and C++ inherits it (and makes it worse)) is that there is no special syntax for introducing a declaration. This means declarations often look like executable code. Another example:
A * a;
Is this multiplying A by a, or is it declaring something? In order to make sense of this line you have to know that A is the name of a type.
The basic rule in C++ is that if something can be parsed as a declaration, it is. In this instance it leads to a strange and surprising result. Function declarations look a lot like function calls, and in particular the ( after the A can be thought of in a couple of ways.
You can get around this in this example with extra parenthesis that remove the compiler's ability to parse the code as a declaration.
B b((A(i)));
In C this isn't ambiguous because there is no function style of constructor call because there are no constructors. A is either the name of a type, or it's the name of a function. It can't be both.
|
1,379,992 | 1,380,129 | Qt doesn't find QStackedWidgets' slot setCurrentWidget | I am writing a wizard-style application in Qt that uses a QStackedWidget to organize the individual pages of the wizard. Now I want to switch between the pages, which should be possible using the function setCurrentWidget(...):
I have a simple main class that instantiates a QWidget audioconfig. Then, it adds this QWidget to a QStackedWidget pageStack using pageStack.addWidget(&audioconfig);.
Later, I want to connect a certain signal from a different QWidget hub to setCurrentWidget(...) of the QStackedWidget in order to switch the page. However, my compiler remarks that
0Object::connect: No such slot QStackedWidget::setCurrentWidget(audioconfig) in /Users/paperflyer/Development/App/main.cpp:41`
There are two things I don't get here:
there clearly is such a function. You can look it up in the class definition of QStackedWidget. What is going on here?
Why is the first character of the compiler output a '0', while my source code clearly and correctly shows it as 'Q'?
Here is the whole code:
int main(int argc, char *argv[])
{
QApplication app(argc,argv);
QStackedWidget pageStack;
CHub hub; // inherits from CWidget
CAudioConfig audioconfig; // ditto
pageStack.addWidget(&hub);
pageStack.addWidget(&audioconfig);
// connect() is a custom signal of hub
QObject::connect(&hub, SIGNAL(configure()), &pageStack, SLOT(setCurrentWidget(&audioconfig)));
pageStack.setGeometry(100,100,700,500);
pageStack.show();
return app.exec();
}
As always, thank you so much for your help!
|
QObject::connect(&hub, SIGNAL(configure()), &pageStack, SLOT(setCurrentWidget(&audioconfig)));
When you connect a signal to a signal/slot, you connect a signature. The actual parameters are passed when emitting the signal. The above should probably be setCurrentWidget(QWidget*), but even so it won't work, because the signature for the signal must match the one of the slot.
Note: I think that if the signal has more parameters than the slot it will still work, provided that the first parameters are the same.
|
1,380,135 | 1,380,364 | Can you evaluate a constructor call to boolean with an overloaded bool()? | Can a constructor call be evaluated to a boolean if the bool() operator is overloaded?
class A
{
public:
A() {};
operator bool() const { return true; }
}
main()
{
if (A a = A())
{
// do stuff
}
}
Is the above code valid, or do I need to implement main like:
int main(int argc, const char* argv[])
{
A a();
if (a)
{
// do stuff
}
}
This code is going to wind up all over the place in my code base, so less lines, increased legibility, and reduced scope are important, and would be improved by this.
Any ideas?
| The code contains a few syntactic and semantic bugs. Let's fix them
class A
{
public:
A() {};
operator bool() { return true; }
};
int main()
{
if (A a = A())
{
// do stuff
}
}
You may choose to change the type in the conversion function to something else. As written, the boolean conversion will also succeed to convert to any integer type. Converting to void* will limit conversion to only bool and void*, which is a commonly used idiom. Yet another and better way is to convert to some private type, called safe bool idiom.
class A
{
private:
struct safe_bool { int true_; };
typedef int safe_bool::*safe_type;
public:
A() {};
operator safe_type() { return &safe_bool::true_; }
};
Back to syntax: If you have an else part, you may use the name of the declared variable, because it's still in scope. It's destroyed after all branches are processed successfully
if(A a = A())
{ ... }
else if(B b = a)
{ ... }
You may also use the same name as before, and the variable will shadow the other variables, but you may not declare the same name in the most outer block of any branch - it will conflict rather than hide with the other declaration.
if(int test = 0)
{ ... }
else
{ int test = 1; /* error! */ }
The technique to declare and initialize a variable is most often used together with dynamic_cast though, but can be perfectly used together with a user defined type like above, too
if(Derived *derived = dynamic_cast<Derived*>(base)) {
// do stuff
}
Note that syntactically, you have to initialize the variable (using the = expression form like for a default argument). The following is not valid
if(ifstream ifs("file.txt")) {
// invalid. Syntactic error
}
|
1,380,192 | 1,380,212 | XML Serialization/Deserialization in C++ | I am using C++ from Mingw, which is the windows version of GNC C++.
What I want to do is: serialize C++ object into an XML file and deserialize object from XML file on the fly. I check TinyXML. It's pretty useful, and (please correct me if I misunderstand it) it basically add all the nodes during processing, and finally put them into a file in one chunk using TixmlDocument::saveToFile(filename) function.
I am working on real-time processing, and how can I write to a file on the fly and append the following result to the file?
Thanks.
| I notice that each TiXmlBase Class has a Print method and also supports streaming to strings and streams.
You could walk the new parts of the document in sequence and output those parts as they are added, maybe?
Give it a try.....
Tony
|
1,380,358 | 1,380,377 | Calling timeconsuming functions from a constructor | What I'm looking right now is a set of classes derived from a common base class. Most, but not all, of the classes require some input parameters which are obtained through modal dialogs. Those dialogs are set up and executed in the constructor of the classes. As long as the dialog isn't finished, the object isn't constructed completely. What problems could arise by delaying the execution of a constructor?
I was thinking of replacing everything with a callback mechanism that is provided to the dialogs to set up the objects or using a factory to get usable objects right after construction. What other patterns are there to solve this situation?
| No "problems" can arise as far as the language is concerned. The constructor is allowed to take as long as it likes.
Where it might be a problem is in the confusion it might cause. Will the programmer using the class be aware that the constructor blocks the thread for a long time?
Without knowing any details of your code, a callback or some other asynchronous mechanism might be better, to avoid blocking the thread.
|
1,380,371 | 1,380,432 | What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs? | It seems that many projects slowly come upon a need to do matrix math, and fall into the trap of first building some vector classes and slowly adding in functionality until they get caught building a half-assed custom linear algebra library, and depending on it.
I'd like to avoid that while not building in a dependence on some tangentially related library (e.g. OpenCV, OpenSceneGraph).
What are the commonly used matrix math/linear algebra libraries out there, and why would decide to use one over another? Are there any that would be advised against using for some reason? I am specifically using this in a geometric/time context*(2,3,4 Dim)* but may be using higher dimensional data in the future.
I'm looking for differences with respect to any of: API, speed, memory use, breadth/completeness, narrowness/specificness, extensibility, and/or maturity/stability.
Update
I ended up using Eigen3 which I am extremely happy with.
| There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matrix math.
I've found it quite nice - it does everything via templates, so it's very flexible, and very fast.
Edit:
After the comments discussion, and edits, I thought I'd throw out some more information about the benefits and downsides to specific implementations, and why you might choose one over the other, given your situation.
GMTL -
Benefits: Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use.
Downsides: API is very focused specifically on rendering and graphics. Doesn't include general purpose (NxM) matrices, matrix decomposition and solving, etc, since these are outside the realm of traditional graphics/geometry applications.
Eigen -
Benefits: Clean API, fairly easy to use. Includes a Geometry module with quaternions and geometric transforms. Low memory overhead. Full, highly performant solving of large NxN matrices and other general purpose mathematical routines.
Downsides: May be a bit larger scope than you are wanting (?). Fewer geometric/rendering specific routines when compared to GMTL (ie: Euler angle definitions, etc).
IMSL -
Benefits: Very complete numeric library. Very, very fast (supposedly the fastest solver). By far the largest, most complete mathematical API. Commercially supported, mature, and stable.
Downsides: Cost - not inexpensive. Very few geometric/rendering specific methods, so you'll need to roll your own on top of their linear algebra classes.
NT2 -
Benefits: Provides syntax that is more familiar if you're used to MATLAB. Provides full decomposition and solving for large matrices, etc.
Downsides: Mathematical, not rendering focused. Probably not as performant as Eigen.
LAPACK -
Benefits: Very stable, proven algorithms. Been around for a long time. Complete matrix solving, etc. Many options for obscure mathematics.
Downsides: Not as highly performant in some cases. Ported from Fortran, with odd API for usage.
Personally, for me, it comes down to a single question - how are you planning to use this. If you're focus is just on rendering and graphics, I like Generic Graphics Toolkit, since it performs well, and supports many useful rendering operations out of the box without having to implement your own. If you need general purpose matrix solving (ie: SVD or LU decomposition of large matrices), I'd go with Eigen, since it handles that, provides some geometric operations, and is very performant with large matrix solutions. You may need to write more of your own graphics/geometric operations (on top of their matrices/vectors), but that's not horrible.
|
1,380,463 | 1,380,496 | Sorting a vector of custom objects | How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a function or a function object) which would operate on one of the fields (as a key for sorting) in the custom object should be used.
Am I on the right track?
| A simple example using std::sort
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};
struct less_than_key
{
inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
{
return (struct1.key < struct2.key);
}
};
std::vector < MyStruct > vec;
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
std::sort(vec.begin(), vec.end(), less_than_key());
Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator< for MyStruct:
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator < (const MyStruct& str) const
{
return (key < str.key);
}
};
Using this method means you can simply sort the vector as follows:
std::sort(vec.begin(), vec.end());
Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a > operator and changing call of sort a bit:
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
bool operator > (const MyStruct& str) const
{
return (key > str.key);
}
};
And you should call sort as:
std::sort(vec.begin(), vec.end(),greater<MyStruct>());
|
1,380,567 | 1,380,602 | Can I use an stl map if I plan to use arbitrary class objects as the key? | I'm new to STL. The thing stumping me about using a map to store arbitrary objects:
std::map<MyClassObj, MyDataObject> MyMap;
is how I find objects. How would MyMap.find (MyClassObjInstance) work for instance? Do I need to implement my own iterator and provide some standard functions which would include some equivalence function? Any examples would be appreciated.
Is there another method to store an associated list of arbitrary objects using standard libraries? I'm already using stl to maintain platform portability, and would prefer not to add another library dependency like BOOST.
| std::map has a third template argument, after key and value, to denote what function is going to be used to compare keys. By default, it is std::less, which in it's turn uses operator<. So if your class has an operator<, it's ok, else you can provide a comparator of your own.
|
1,380,585 | 1,380,613 | map of vectors in STL? | I want to have a map of vectors, (but I don't want to use pointer for the internal vector), is it possible?
// define my map of vector
map<int, vector<MyClass> > map;
// insert an empty vector for key 10. # Compile Error
map.insert(pair<int, vector<MyClass> >(10, vector<MyClass>));
I know that if I have used pointer for vector, as follows, it would be fine, but I wonder if I can avoid using pointer and use the above data structure (I don't want to manually delete)
// define my map of vector
map<int, vector<MyClass>* > map;
// insert an empty vector for key 10.
map.insert(pair<int, vector<MyClass>* >(10, new vector<MyClass>));
| The first data structure will work. You might want to typedef some of the code to make future work easier:
typedef std::vector<MyClass> MyClassSet;
typedef std::map<int, MyClassSet> MyClassSetMap;
MyClassSetMap map;
map.insert(MyClassSetMap::value_type(10, MyClassSet()));
or (thanks quamrana):
map[10] = MyClassSet();
|
1,380,653 | 1,381,910 | Why do you need to append an L or F after a value assigned to a C++ constant? | I have looked at quite a few places online and can't seem to find a good explanation as to why we should append an F or L after a value assigned to a C++ constant. For example:
const long double MYCONSTANT = 3.0000000L;
Can anyone explain why that is necessary? Doesn't the type declaration imply the value assigned to MYCONSTANT is a long double? What is the difference between the above line and
const long double MYCONSTANT = 3.0000000; // no 'L' appended
Whew!
| Floating-point constants have type double by default in C++. Since a long double is more precise than a double, you may lose significant digits when long double constants are converted to double. To handle these constants, you need to use the L suffix to maintain long double precision. For example,
long double x = 8.99999999999999999;
long double y = 8.99999999999999999L;
std::cout.precision(100);
std::cout << "x=" << x << "\n";
std::cout << "y=" << y << "\n";
The output for this code on my system, where double is 64 bits and long double 96, is
x=9
y=8.9999999999999999895916591441391574335284531116485595703125
What's happening here is that x gets rounded before the assignment, because the constant is implicitly converted to a double, and 8.99999999999999999 is not representable as a 64-bit floating point number. (Note that the representation as a long double is not fully precise either. All of the digits after the first string of 9s are an attempt to approximate the decimal number 8.99999999999999999 as closely as possible using 96 binary bits.)
In your example, there is no need for the L constant, because 3.0 is representable precisely as either a double or a long double. The double constant value is implicitly converted to a long double without any loss of precision.
The case with F is not so obvious. It can help with overloading, as Zan Lynx points out. I'm not sure, but it may also avoid some subtle rounding errors (i.e., it's possible that encoding as a float will give a different result from encoding as a double then rounding to a float).
|
1,380,829 | 1,380,926 | Is extern "C" only required on the function declaration? | I wrote a C++ function that I need to call from a C program. To make it callable from C, I specified extern "C" on the function declaration. I then compiled the C++ code, but the compiler (Dignus Systems/C++) generated a mangled name for the function. So, it apparently did not honor the extern "C".
To resolve this, I added extern "C" to the function definition. After this, the compiler generated a function name that is callable from C.
Technically, the extern "C" only needs to be specified on the function declaration. Is this right? (The C++ FAQ has a good example of this.) Should you also specify it on the function definition?
Here's an example to demonstrate this:
/* ---------- */
/* "foo.h" */
/* ---------- */
#ifdef __cplusplus
extern "C" {
#endif
/* Function declaration */
void foo(int);
#ifdef __cplusplus
}
#endif
/* ---------- */
/* "foo.cpp" */
/* ---------- */
#include "foo.h"
/* Function definition */
extern "C" // <---- Is this needed?
void foo(int i) {
// do something...
}
My issue may be the result of incorrectly coding something, or I may have found a compiler bug. In any case, I wanted to consult stackoverflow to make sure I know which is technically the "right" way.
| The 'extern "C"' should not be required on the function defintion as long as the declaration has it and is already seen in the compilation of the definition. The standard specifically states (7.5/5 Linkage specifications):
A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.
However, I generally do put the 'extern "C"' on the definition as well, because it is in fact a function with extern "C" linkage. A lot of people hate when unnecessary, redundant stuff is on declarations (like putting virtual on method overrides), but I'm not one of them.
|
1,380,907 | 1,380,932 | Error calling function and passing a reference-to-pointer with a derived type | Can somebody explain why the following code is not valid? Is it because the offset for the variable named d is different than the variable named b?
class Base { public: int foo; };
class Derived : public Base { public: int bar; };
int DoSomething( Base*& b ) { return b->foo; }
Base* b = new Derived;
Derived* d = new Derived;
int main()
{
DoSomething( d );
}
This is the error that the online Comeau C++ compiler gives:
"ComeauTest.c", line 12: error: a reference of type "Base *&" (not const-qualified)
cannot be initialized with a value of type "Derived *"
DoSomething( d );
^
This is a similar question but is different because in my example, I am declaring d as a pointer type: Passing references to pointers in C++
Note that this does compile when I pass b to DoSomething.
| Imagine you could do that. The reference is not const, so it's possible for DoSomething to assign to the pointer and that will be visible in the caller. In particular, inside DoSomething it's possible for us to change the pointer to point to something that isn't an instance of Derived. If the caller then tries to do Derived-specific things to the pointer after we return, it'll explode.
|
1,381,078 | 1,381,368 | Parallel reads from STL containers | It is safe to read a STL container from multiple parallel threads. However, the performance is terrible. Why?
I create a small object that stores some data in a multiset. This makes the constructors fairly expensive ( about 5 usecs on my machine. ) I store hundreds of thousands of the small objects in a large multiset. Processing these objects is an independent business, so I split the work between threads running on a multi-core machine. Each thread reads the objects it needs from the large multiset, and processes them.
The problem is that the reading from the big multiset does not proceed in parallel. It looks like the reads in one thread block the reads in the other.
The code below is the simplest I can make it and still show the problem. First it creates a large multiset containing 100,000 small objects each containing its own empty multiset. Then it calls the multiset copy constructor twice in series, then twice again in parallel.
A profiling tool shows that the serial copy constructors take about 0.23 secs, whereas the parallel ones take twice as long. Somehow the parallel copies are interfering with each other.
// a trivial class with a significant ctor and ability to populate an associative container
class cTest
{
multiset<int> mine;
int id;
public:
cTest( int i ) : id( i ) {}
bool operator<(const cTest& o) const { return id < o.id; }
};
// add 100,000 objects to multiset
void Populate( multiset<cTest>& m )
{
for( int k = 0; k < 100000; k++ )
{
m.insert(cTest(k));
}
}
// copy construct multiset, called from mainline
void Copy( const multiset<cTest>& m )
{
cRavenProfile profile("copy_main");
multiset<cTest> copy( m );
}
// copy construct multiset, called from thread
void Copy2( const multiset<cTest>& m )
{
cRavenProfile profile("copy_thread");
multiset<cTest> copy( m );
}
int _tmain(int argc, _TCHAR* argv[])
{
cRavenProfile profile("test");
profile.Start();
multiset<cTest> master;
Populate( master );
// two calls to copy ctor from mainline
Copy( master );
Copy( master );
// call copy ctor in parrallel
boost::thread* pt1 = new boost::thread( boost::bind( Copy2, master ));
boost::thread* pt2 = new boost::thread( boost::bind( Copy2, master ));
pt1->join();
pt2->join();
// display profiler results
cRavenProfile print_profile;
return 0;
}
Here is the output
Scope Calls Mean (secs) Total
copy_thread 2 0.472498 0.944997
copy_main 2 0.233529 0.467058
| You mentioned copy constructors. I assume that these also allocate memory from the heap?
Allocating heap memory in multiple threads is a big mistake.
The standard allocator is probably a single pool locked implementation. You need to either not use heap memory (stack allocate) or you need a thread optimized heap allocator.
|
1,381,627 | 1,381,696 | Get a pointer to structure in a map C++ | Ok so I have struct like this
typedef struct
{
float x;
float y;
char name[];
} pTip;
And another struc
typdef struct
{
float xx;
float yy;
pTip *tip;
}finalTip;
I create and populate a map<string, pTip> maps
That works fine.
I am now trying to generate vector of finalTips
I do:
map<string, pTip>::const_iterator iter = maps.find(p_name);
So it works great my iterator now has what I need and I can extract info with
(iter->second).x
But I want to now using that iterator save it in my finalTip struc obj final
So I tried:
finalTip final;
final.tip = iter->second;
And for this case I get error:
error: cannot convert 'const pTip' to 'pTip*' in assignment
So I fixed by:
*final.tip = iter->second;
Was this correct fix or am I doing it wrong.
This seems to work but I want to make sure I am doing it right
| You want
final.tip = &iter->second;
Since iter is a map<string, pTip> iterator, iter->second is a reference to pTip. Take its address with & to get a pointer.
Unfortunately, since you have a const_iterator, &iter->second will be a (const pTip *)
So, either get a non-const iterator, or make the .tip member a const pTip *, or if you're desperate, cast away the const:
final.tip = const_cast<pTip*>(&iter->second);
Final note: you may prefer pTip const* to const pTip * - they mean the same thing.
|
1,381,646 | 1,381,802 | How Do I use LoadLibrary in COM Accross Multiple Threads? | Let's say that I have the following code that's run in one thread of a multi-threaded COM application:
// Thread 1
struct foo {
int (*DoSomething)(void ** parm);
};
HMODULE fooHandle = LoadLibrary("pathToFoo");
typedef int (*loadUpFooFP)(foo ** fooPtrPtr);
loadUpFooFP loadUpFoo;
loadUpFoo = (loadUpFooFP)GetProcAddress(fooHandle, "fooLoader");
foo * myFoo;
loadUpFoo(&myFoo);
This all works great and I can then call
myFoo->DoSomething(&parmPtr);
This works, too! Now, another thread comes along and loads up its foo:
// Thread 2
foo * myFooInThread2;
loadUpFoo(&myFooInThread2);
And this, too, works great. In thread 2 I can call DoSomething:
// Thread 2
myFooInThread2->DoSomething(&anotherParmPtr);
Now, when thread 1 eventually goes away, I have a problem. I notice that debugging in Visual Studio that the address of DoSomething can no longer be evaluated. After the first thread dies, when I call:
myFooInThread2->DoSomething(&anotherParmPtr);
I get an access violation. The myFooInThread2 pointer is still valid, but the function pointer was not. This function pointer was set by a call into loadUpFoo which in turn was in a dll loaded by LoadLibrary.
My question is: where do I start looking for the reason this is failing? Is it some problem with the way the external DLL (that I load with LoadLibrary) is setting the function pointer in my foo struct? Or is it something to do with differing threads using the same library? Or, could it somehow be related to my usage of COM in this application (would calling CoUninitialize in the first thread somehow free this memory or library)?
I can provide more details on the COM setup if that looks like it could be responsible. Thanks!
edit: Thanks for the suggestions so far. The foo struct is opaque - I don't really know much about its implementation. The foo struct is declared in a header I import. There are no reference counting methods that I explicitly call and there are no other interactions with the library that's loaded with LoadLibrary. I'm pretty sure the foo struct is not memory mapped to some COM class, but like I said it's opaque and I can't say for sure.
The foo pointers' lifetimes are properly managed (not deleted).
The foo structure is an encryption library, so I'm not at liberty to divulge any more. At this point, I'm confident that there is nothing inherently wrong with my usage of LoadLibrary across different threads and within a COM application (and I suppose that the function pointer memory cleanup is being caused by something in the library itself outside of my control).
| There's nothing COM related in the code you've shown. LoadLibrary is not thread-specific, so once you have the handle to the lib, you can reuse it from all your threads. Same applies to the pointer to the fooLoader method.
However, there certainly could be something COM-specific inside fooLoader. Also, what's not clear here is what is the lifetime control of the foo instances.
From the fact that you mention COM and the funky behavior you see, I have the sneaky suspicion that foo is actually a memory map of a COM object's vtable and fooLoader is DllGetClassObject or another factory method that creates COM objects.. :-)
In any case, the most probable explanation for the foo instance becoming invalid would be that it is ref-counted and DoSomething calls AddRef()/Release() causing it to self-destroy.
To pinpoint exactly what's going on, you'll have to provide a bit more information on what fooLoader does and why you think your code is COM related.
|
1,381,757 | 1,381,801 | Good multithreading guides? | I'm looking for a good guide/tutorial on multithreading in C++ (and ideally in general). Can anyone point me to a good online resource?
EDIT: I intend to familiarize myself with either the boost threading library or the one from Poco.
| The Dr. Dobbs article "The Boost.Threads Library" is a short introduction to the subject, using one of the Boost C++ Libraries.
|
1,381,798 | 1,385,051 | function calling convention with boost::function_types | I've just been experimenting with the boost::function_types library recently, and I've come across a bit of a snag. I want to find out the calling convention of a given function, however I'm not quite sure how to do this. Here's what I have so far:
This produces an error about how it cannot find the *_cc tag values inside each if statement. I suspect it may have something to do with the way I'm defining the macros; the documentation isn't very clear about how to setup extra calling conventions with your compiler... Any help here would be appreciated.
Thanks,
EDITED: got it working, seems like I needed to include config/config.hpp, as below:
#define BOOST_FT_COMMON_X86_CCs 1
#include <boost/function_types/config/config.hpp>
#include <boost/type_traits.hpp>
#include <boost/function_types/property_tags.hpp>
#include <boost/function_types/is_function.hpp>
#include <boost/function_types/is_function_pointer.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/function_arity.hpp>
template<class F>
inline void parse_cc(F f, func_info_s& out) {
out.cc = cc_err;
if (boost::function_types::is_function<F, stdcall_cc>::value == true) {
out.cc = cc_stdcall;
} else if (boost::function_types::is_function<F, fastcall_cc>::value == true) {
out.cc = cc_fastcall;
} else if (boost::function_types::is_function<F, cdecl_cc>::value == true) {
out.cc = cc_cdecl;
}
}
| It seems like I was simply missing one of the header files (config/config.hpp)
#define BOOST_FT_COMMON_X86_CCs 1
#include <boost/function_types/config/config.hpp>
#include <boost/type_traits.hpp>
#include <boost/function_types/property_tags.hpp>
#include <boost/function_types/is_function.hpp>
#include <boost/function_types/is_function_pointer.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/function_arity.hpp>
template<class F>
inline void parse_cc(F f, func_info_s& out) {
out.cc = cc_err;
if (boost::function_types::is_function<F, stdcall_cc>::value == true) {
out.cc = cc_stdcall;
} else if (boost::function_types::is_function<F, fastcall_cc>::value == true) {
out.cc = cc_fastcall;
} else if (boost::function_types::is_function<F, cdecl_cc>::value == true) {
out.cc = cc_cdecl;
}
}
|
1,381,937 | 1,381,946 | SetJmp/LongJmp: Why is this throwing a segfault? | The following code summarizes the problem I have at the moment. My current execution flow is as follows and a I'm running in GCC 4.3.
jmp_buf a_buf;
jmp_buf b_buf;
void b_helper()
{
printf("entering b_helper");
if(setjmp(b_buf) == 0)
{
printf("longjmping to a_buf");
longjmp(a_buf, 1);
}
printf("returning from b_helper");
return; //segfaults right here
}
void b()
{
b_helper();
}
void a()
{
printf("setjmping a_buf");
if(setjmp(a_buf) == 0)
{
printf("calling b");
b();
}
printf("longjmping to b_buf");
longjmp(b_buf, 1);
}
int main()
{
a();
}
The above execution flow creates a segfault right after the return in b_helper. It's almost as if only the b_helper stack frame is valid, and the stacks below it are erased.
Can anyone explain why this is happening? I'm guessing it's a GCC optimization that's erasing unused stack frames or something.
Thanks.
| You can only longjmp() back up the call stack. The call to longjmp(b_buf, 1) is where things start to go wrong, because the stack frame referenced by b_buf no longer exists after the longjmp(a_buf).
From the documentation for longjmp:
The longjmp() routines may not be called after the routine which called the setjmp() routines returns.
This includes "returning" through a longjmp() out of the function.
|
1,381,939 | 1,381,980 | Taking iterators two at a time? | I'll often represent and process polylines like so:
typedef std::vector< Point_t > Polyline_t;
double PolylineLength(const Polyline_t& line)
{
double len = 0.0;
for( size_t i = 0; i < line.size()-1; ++i )
len += (line[i+1]-line[i+0]).length();
return len;
}
The most straightforward conversion to bidirectional iterators that I came up with is:
typedef std::list< Point_t > Polyline_t;
typedef Polyline_t::const_iterator Polyline_t_cit;
double PolylineLength(const Polyline_t& line)
{
double len = 0.0;
Polyline_t_cit last = line.end();
last--;
for( Polyline_t_cit i = line.begin(); i != last; ++i )
{
const Point_t& beg = *i;
const Point_T& end = *(++i);
len += (end - beg).length();
--i;
}
return len;
}
Is there a more succinct way to express this sort of two-at-time processing with iterators?
| I would keep two iterators, and then check whether the second iterator has reached end. This will make it not require bidirectional iterators anymore:
typedef std::list< Point_t > Polyline_t;
typedef Polyline_t::const_iterator Polyline_t_cit;
double PolylineLength(const Polyline_t& line)
{
double len = 0.0;
Polyline_t_cit f = line.begin(), s(f), end = line.end();
for(++s; s != end; ++f, ++s) {
len += (*s - *f).length();
}
return len;
}
|
1,382,217 | 1,382,399 | Should I be worried about g++ warnings saying 'inlining failed'? | In a project I'm working on at the office, when we compile a release build (with -Os) we get hundreds of warnings from g++ saying that inlining has failed. Most of these warnings seem to come from boost, however some come from our own library headers (binary .dylibs that we're linking to). Can these warnings generally be safely ignored, or are they something I should be worried about?
Note: We're using g++ 4.0 on Mac OS X
| g++ is alerting at what's essentially, strictly a PERFORMANCE problem -- you're requesting inline implementations that just can't be inlined. If your use of inline doesn't really matter, you should remove it (compilers ARE able to inline functions without that hint, you know!-), but in terms of code correctness, you can ignore the warning. If your use of inline really DOES matter, i.e., is crucial to your performance (as opposed to being a silly premature optimization), the warning is telling you to rework your code so it can be achieved (worst case, by moving down to macros -- sigh, but, when you must, you MUST!-).
|
1,382,273 | 1,382,361 | Sorting a Doubly Linked List C++ | Trying to do it through a loop that traverses through the list.
In the loop I'm feeding the head node into a sorting function that I have defined and then I'm using strcmp to find out if which name in the node should come first.
It is not working because writing the names too early.
Im comparing them all linearly by going down the list one node at a time and not going back to see if the first should come before the last. That part explained would be helpful.
The two functions that are most important to me now are defined as follows:
I have tried my best to do what I think is right for the sorting function.
void list::displayByName(ostream& out) const
{
list *ListPtr = NULL;
node *current_node = headByName;
winery *wine_t = new winery();
// winery is another class object type
// im allocating it to prevent a crash when I call it.
while ( current_node != NULL )
{
*(wine_t) = current_node->item;
wine_t = ListPtr->sort( current_node );
out << wine_t << endl;
current_node = current_node->nextByName;
}
delete wine_t;
}
winery * const list::sort( node * current_node ) const
{
// current_node is the first node.
const char *SecondName = NULL, *FirstName = NULL;
winery *wine_t = new winery();
if ( current_node != NULL )
{
SecondName = current_node->item.getName();
current_node = current_node->nextByName;
FirstName = current_node->item.getName();
}
if ( strcmp( FirstName, SecondName ) == -1 )
{
*(wine_t) = current_node->item;
FirstName = NULL;
SecondName = NULL;
return wine_t;
}
else if ( strcmp( FirstName, SecondName ) == 1 )
{
*(wine_t) = current_node->item;
FirstName = NULL;
SecondName = NULL;
return wine_t;
}
else return wine_t;// then the strings are equal
FirstName = NULL;
SecondName = NULL;
return wine_t;
}
And I started to develop my nodes here:
void list::insert(const winery& winery)
{
node *current_node = new node( winery );
if ( headByName == NULL )
{
headByName = current_node;
headByRating = current_node;
tail = headByName;
current_node->prev = current_node;
}
else
{
current_node->prev = tail;
tail->nextByName = current_node;
}
tail = current_node;
current_node = NULL;
}
I think its correct in that function above. Could I possibly get away with sorting it there?
Below are my varaibles that I am working with:
public list
{
...
void insert(const winery& winery);
void displayByName(ostream& out) const;
}
private:
struct node
{
node(const winery& winery); // constructor
winery item;
node * prev;
node * nextByName;
node * nextByRating;
};
winery * const sort(node*) const;
node * headByName;
node * headByRating;
node * tail;
};
Any help is appreciated.
Thanks very much =)
| From what I understand, you want list::sort to find the least node in the list which is greater than the input.
To do this, you need to iterate through all the elements and keep the current least-but-greater node found.
Something like this:
node * const list::sort( node * given_node ) const
{
if ( given_node == NULL )
{
return NULL;
}
// Smallest node found which is greater than given_node.
node * least_found_node = NULL;
// Node we are looking at right now.
node * current_node = given_node->nextByName;
// Go through all nodes.
while ( current_node && current_node != given_node )
{
// Is this node bigger than the given node?
if ( strcmp( current_node->item.getName(), given_node->item.getName() ) < 0 )
{
// Is this node smaller than the smallest node we know of?
if ( least_found_node == NULL ||
((strcmp( current_node->item.getName(), least_found_node->item.getName() ) > 0) )
{
// We found a better node.
least_found_node = current_node;
}
}
current_node = current_node->nextByName;
}
return least_found_node;
}
Now change your display function to use it like this:
void list::displayByName(ostream& out) const
{
// Find first node initially.
node * current_node = sort( NULL );
while ( current_node != NULL )
{
// Print node.
out << current_node->item.getName();
// Find next node in sorted output.
current_node = sort( current_node );
}
}
This part keeps calling sort until sort returns NULL. The first call to sort is with NULL so the lowest item is found (that is, the first in the sorted list). sort returns NULL if there are no more nodes larger than current_node, thus terminating the loop.
|
1,382,318 | 1,382,630 | Binding lvalue to a reference | I think I am missing smth back in my theoretical background on this thing. I know there were similar posts but I still do not get it.
I have such a code:
void somefunc1(Word &Key)
{
somefunc2(Key);
}
void somefunc2(char &char1)
{
return;
}
compiler generates me an error here:
somefunc2(Key);
[BCC32 Error] Unit1.cpp(830): E2357 Reference initialized with 'unsigned short', needs lvalue of type 'char'
I found out that it is because of the ANSI 2003 regulation on C++ dealing with temporaries and references but I still do not get what is wrong here.
when I do c-style conversion:
somefunc2( *(char*)&Key )
it resolves an issue.
Can anyone hint me what is wrong and why is it wrong?
| Temporaries cannot be bound to non-constant references.
You should have written this:
void somefunc2(const char &char1)
{
return;
}
|
1,382,459 | 1,382,479 | My 'cout' isn't giving correct value - why? | Simple "sum of digits" code. It compiles but when executed, the last cout gives a "0" for the num int rather than the actual user-input number.
Feel free to copy and paste this into your own compiler, if you're so inclined, to see what I mean.
How can I get this to output the correct "num" value?
~~~
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
cout << "Please type any non-negative integer: ";
cin >> num;
while ( num > 0 ) {
sum += num % 10;
num /= 10;
}
cout << "The sum of the digits of " << num << " is " << sum << "\n";
system("PAUSE");
return 0;
}
| You've been modifying num all along until it becomes 0 (that's what your while ( num > 0 ) statement ensures!), so OF COURSE it's 0 at the end! If you want to emit what it was before, add e.g. int orig=num; before the loop, and emit orig at the end.
|
1,382,529 | 1,383,152 | Calling C++ (not C) from Common Lisp? | I am wondering if there is some way to call C++ code from Common Lisp (preferably portably, and if not, preferably in SBCL, and if not, well, then Clozure, CLisp or ECL).
The C++ would be called inside loops for numeric computation, so it would be nice if calls were fast.
CFFI seems to not support this:
"The concept can be generalized to
other languages; at the time of
writing, only CFFI's C support is
fairly complete, but C++ support is
being worked on."
(chapter 4 of the manual)
SBCL's manual doesn't mention C++ either; it actually says
This chapter describes SBCL's
interface to C programs and libraries
(and, since C interfaces are a sort of
lingua franca of the Unix world, to other programs and libraries in
general.)
The C++ code uses OO and operator overloading, so it really needs to be compiled with g++.
And as far as I know, I can have a C++ main() function and write wrappers for C functions, but not the other way around -- is that true?
Anyway... Is there some way to do this?
Thank you!
| Oh, wait!
It seems that there is a trick I can use!
I write a wrapper in C++, declaring wrapper functions extern "C":
#include "lib.h"
extern "C" int lib_operate (int i, double *x) {
...
}
The header file lib.h, which can be called from both C and C++, is:
#if __cplusplus
extern "C" {
#endif
int lib_operate (int i, double *x);
#if __cplusplus
}
#endif
Then compile with:
g++ -c lib.cpp
gcc -c prog.c
gcc lib.o prog.o -lstdc++ -o prog
Seems to work for a toy example! :-)
So, in Common Lisp I'd call the wrapper after loading libstdc++.
Anyway, thank you for your answers!
|
1,382,537 | 1,383,581 | Setting QMainWindow at the center of screen | My QMainWindow contains a QGraphicsView, which should've minimum width and height. So, I've used the following code in the QMainWindow constructor:
ui.graphicsView->setMinimumHeight(VIEWWIDTH);
ui.graphicsView->setMinimumWidth(VIEWWIDTH);
Then I used following code to set QMainWindow at the center of the screen:
QRect available_geom = QDesktopWidget().availableGeometry();
QRect current_geom = frameGeometry();
setGeometry(available_geom.width() / 2 - current_geom.width() / 2,
available_geom.height() / 2 - current_geom.height() / 2,
current_geom.width(),
current_geom.height());
But it is not set at the center of the screen. If I omit setMinimumHeight() and setMinimumWidth() from QGraphicsView, then the main window is set at the center of the screen. How to overcome this problem? I'm using Qt 4.5.2.
Thanks.
| The problem you are encountering is that Qt will delay many calculations as long as it can. When you set the minimum width and height of your graphics view, it sets a flag somewhere that the window the graphics view is in needs re-layed out. However, it won't do that until it has to... a few milliseconds before it is actually shown on screen. So, when you call rect() on your main window, you are getting the old rectangle, and not the new one.
My best recommendation is to extend the size change event in your main window, and adjust the positioning in that event. You may also have to flag when the window has actually been shown, so that you don't reposition the window if the user resizes it after it has been shown.
Alternately, you could try repositioning the window by extending the show event function and doing it there. It would probably happen before the user actually sees the window, but might flicker on occasion.
|
1,382,540 | 1,382,566 | Static cast vs. dymamic cast for traversing inheritance hierarchies | I saw one book on C++ mentioning that navigating inheritance hierarchies using static cast is more efficient than using dynamic cast.
Example:
#include <iostream>
#include <typeinfo>
using namespace std;
class Shape { public: virtual ~Shape() {}; };
class Circle : public Shape {};
class Square : public Shape {};
class Other {};
int main() {
Circle c;
Shape* s = &c; // Upcast: normal and OK
// More explicit but unnecessary:
s = static_cast<Shape*>(&c);
// (Since upcasting is such a safe and common
// operation, the cast becomes cluttering)
Circle* cp = 0;
Square* sp = 0;
// Static Navigation of class hierarchies
// requires extra type information:
if(typeid(s) == typeid(cp)) // C++ RTTI
cp = static_cast<Circle*>(s);
if(typeid(s) == typeid(sp))
sp = static_cast<Square*>(s);
if(cp != 0)
cout << "It's a circle!" << endl;
if(sp != 0)
cout << "It's a square!" << endl;
// Static navigation is ONLY an efficiency hack;
// dynamic_cast is always safer. However:
// Other* op = static_cast<Other*>(s);
// Conveniently gives an error message, while
Other* op2 = (Other*)s;
// does not
} ///:~
However, both dynamic cast and static cast (as implemented above) need RTTI enabled for such navigation to work. It's just that dynamic cast requires the class hierarchy to be polymorphic (i.e. base class having at least one virtual function).
Where does this efficiency gain for static cast come from?
The book does mention that dynamic cast is the preferred way for doing type-safe downcasting.
| static_cast per se DOESN'T need RTTI -- typeid does (as does dynamic_cast), but that's a completely different issue. Most casts are just telling the compiler "trust me, I know what I'm doing" -- dynamic_cast is the exception, it asks the compiler to check at runtime and possibly fail. That's the big performance difference right there!
|
1,382,586 | 1,382,743 | Architecture for Qt application with Lua scripting - pause execution | My embedded project contains a Qt application for the PC which is mainly a simulator for debugging and testing. In the application I can create several widgets which represent either my embedded software or simulate the hardware controlled by the application or can generate external inputs for testing.
I plan to improve the application by adding Lua scripting so that the widgets can be created or controlled from a script. I need an elegant way for single stepping the scripts.
I plan scripts like:
createThermometerWidget(10,20,30)
while time < maxTime do
setTemperature(20+time/1000)
pauseSimulation()
time = time + 1
end
The custom function pauseSimulation should stop the Lua script, enable the Qt event loop to run so that interaction with the software is possible (seting other inputs for example) and after pressing a button the script will continue.
My first idea was to create a separate thread for the Lua execution which will be stopped by pauseSimulation and released by the button. But Qt widgets cannot be created from non-main thread so that I will have to create all widgets in the main thread and pass all constructor parameters from Lua functions to the main thread.
Is there a more smooth way?
| Coroutines are one approach to implementing this. Your pauseSimulation() can internally call coroutine.yield(), and be restarted later by a call to coroutine.resume() from the button's action. The problem is that your UI is at the mercy of your script fragments, since the only way to halt a running coroutine is for it to eventally call yield().
Alternatively, you can use the Lanes module to put part of your Lua application into a separate thread. You would use a Linda to pass messages from the main Qt widget thread to your simulator's worker thread. This would have the advantage that the UI thread is not blocked by the simulation which runs in its own thread.
|
1,382,628 | 1,382,645 | STL: Stores references or values? | I've always been a bit confused about how STL containers (vector, list, map...) store values. Do they store references to the values I pass in, or do they copy/copy construct +store the values themselves?
For example,
int i;
vector<int> vec;
vec.push_back(i);
// does &(vec[0]) == &i;
and
class abc;
abc inst;
vector<abc> vec;
vec.push_back(inst);
// does &(vec[0]) == &inst;
Thanks
| STL Containers copy-construct and store values that you pass in. If you want to store objects in a container without copying them, I would suggest storing a pointer to the object in the container:
class abc;
abc inst;
vector<abc *> vec;
vec.push_back(&inst);
This is the most logical way to implement the container classes to prevent accidentally storing references to variables on defunct stack frames. Consider:
class Widget {
public:
void AddToVector(int i) {
v.push_back(i);
}
private:
vector<int> v;
};
Storing a reference to i would be dangerous as you would be referencing the memory location of a local variable after returning from the method in which it was defined.
|
1,383,038 | 1,383,124 | 3d Realtime Software Renderer Open Source | Is there a good 3d realtime software renderer with features similar to OpenGL/DirectX? Something similar of what cairo or anti-grain do for 2d, but in 3d.
I actually just know Mesa witch has a software OpenGL implementation , and Coco3d.
It should be open source :)
| For a pixel rendering engine why not have look at the DOOM rendering engine sources.
Another smaller and more standard API/OpenGL implementation called TinyGL could be something to look at too.
|
1,383,465 | 1,400,047 | How can I append images to a multi-page image? | I need to programatically append to a multi-page TIFF or PDF a new image. The problem is that the individual images (that compose the multi-page one) have large resolutions and ImageMagick first loads the entire multi-page image into memory, which consumes all the system's memory.
I need to be able to append to a multi-page image without having to load the entire image into memory. Is this possible with ImageMagick? Which C/C++ functions should I use?
| I'm not sure it's possible in ImageMagick.
For TIFF, what you need to do is read TIFF Directories out of one TIFF and create new ones in the one you are appending to, and then copy the encoded image via a buffer. There is no need to decode the image to do this, but you have to be careful to do it correctly and bring over any of the directories associated with the page (like the associated meta-data).
I think that libtiff (which ImageMagick wraps) provides functions that can help you do this.
For PDF, it's also hard -- this page has some alternatives:
http://ansuz.sooke.bc.ca/software/pdf-append.php
There are also many 3rd party SDKs that can manipulate PDF (ActivePDF, PDFTron, Amyuni).
Disclaimer: I work for Atalasoft: we have a .NET SDK that has this functionality for TIFF (and image-only PDF). It can be called via C++/CLI, but not sure if you are on Windows.
|
1,383,485 | 1,383,522 | Call a function lower in the script from a function higher in the script | I'm trying to come up with a way to make the computer do some work for me. I'm using SIMD (SSE2 & SSE3) to calculate the cross product, and I was wondering if it could go any faster. Currently I have the following:
const int maskShuffleCross1 = _MM_SHUFFLE(3,0,2,1); // y z x
const int maskShuffleCross2 = _MM_SHUFFLE(3,1,0,2); // z x y
__m128 QuadCrossProduct(__m128* quadA, __m128* quadB)
{
// (y * other.z) - (z * other.y)
// (z * other.x) - (x * other.z)
// (x * other.y) - (y * other.x)
return
(
_mm_sub_ps
(
_mm_mul_ps
(
_mm_shuffle_ps(*quadA, *quadA, maskShuffleCross1),
_mm_shuffle_ps(*quadB, *quadB, maskShuffleCross2)
),
_mm_mul_ps
(
_mm_shuffle_ps(*quadA, *quadA, maskShuffleCross2),
_mm_shuffle_ps(*quadB, *quadB, maskShuffleCross1)
)
)
);
}
As you can see, there are four _mm_shuffle_ps's in there, and I wondered if I could replace them with a combination of _mm_unpackhi_ps and _mm_unpacklo_ps which return a2 a3 b2 b3 and a0 a1 b0 b1 respectively and are slightly faster.
I couldn't figure it out on paper, but I thought of a solution. What if let the computer bruteforce the steps required? Just recursively step through the different options and see what gives the correct answer.
I got it work with multiply, it returns this when I want it to return (3, 12, 27, 0):
startA = _mm_set_ps(1.00, 2.00, 3.00, 0.00);
startB = _mm_set_ps(3.00, 3.00, 3.00, 0.00);
result0 = _mm_mul_ps(startA, startB);
// (3.00, 6.00, 9.00, 0.00)
result1 = _mm_mul_ps(startA, result0);
// (3.00, 12.00, 27.00, 0.00)
Very nice, if I say so myself.
However, when I wanted to implement divide I stumbled on a problem. Multiply doesn't just have to call multiply, it also has to call divide. Okay, so we put divide above multiply. But divide doesn't just have to call divide, it also has to call multiply, which is lower in the script, so it doesn't exist yet.
I started with an empty console application in Visual C++ and put everything in QuadTests.cpp.
How do I make sure these two functions can call each other?
Thanks in advance.
| Just to confirm, your problem is that functions arranged like this don't work, because doStuff isn't declared by the time you call it from getFoo:
int getFoo(int bar) {
doStuff(bar + 1);
}
int doStuff(bar) {
if (bar == 2) {
return getFoo(bar);
}
return bar * 8;
}
To fix this, you need to make a forward declaration of int doStuff(int). Often, this is done with a header file -- either way, you just need to add something like this:
// #includes, etc. go here
int doStuff(int);
int getFoo(int);
// methods follow
|
1,383,617 | 1,383,638 | How to check if a file exists and is readable in C++? | I've got a fstream my_file("test.txt"), but I don't know if test.txt exists. In case it exists, I would like to know if I can read it, too. How to do that?
I use Linux.
| I would probably go with:
ifstream my_file("test.txt");
if (my_file.good())
{
// read away
}
The good method checks if the stream is ready to be read from.
|
1,383,650 | 1,383,672 | C++ Inheritance/VTable questions | Update: Replaced the destructor example with a straight up method call example.
Hi,
If I have the following code:
class a
{
public:
virtual void func0(); // a has a VTable now
void func1();
};
class b : public a
{
public:
void func0() { a::func0(); }
void func2();
};
Is there a VTable in B? B has no virtual functions but calls a::func0() from b::func0()
Does func1 reside in a VTable? It's not virtual.
Does func2 reside in a VTable?
Will the answers to the above be different if there wasn't a a::func0() call in b::func0()?
Thanks
| If you declare virtual functions you should also declare your destructor virtual ;-).
B has a virtual table, because it has a virtual function, namely func0(). If you declare a function (including a destructor) virtual in a base class, all its derived classes will have the function with same signature virtual as well. And it will cause them to have a vtable. Moreover, B would have the vtable even if you didn't declare func0 in it explicitly.
Non-virtual functions are not referenced through vtables.
See 2.
No. Classes' vtables are constructed based on class declarations. The bodies of class' functions (let alone other functions) are not taken into account. Therefore, B has a vtable, because its function func0() is virtual.
There also is a tricky detail, although it's not the gist of your question. You declared your function B::func0() as inline. In gcc compiler, if a virtual function is declared inline, it retains its slot in virtual table, the slot pointing to a special function emitted for that inline one (that counts as taking its address, which makes the inline emitted). That means, whether the funciton is inline doesn't influence amount of slots in vtable and its necessity for a class.
|
1,384,007 | 1,384,044 | Conversion constructor vs. conversion operator: precedence | Reading some questions here on SO about conversion operators and constructors got me thinking about the interaction between them, namely when there is an 'ambiguous' call. Consider the following code:
class A;
class B {
public:
B(){}
B(const A&) //conversion constructor
{
cout << "called B's conversion constructor" << endl;
}
};
class A {
public:
operator B() //conversion operator
{
cout << "called A's conversion operator" << endl;
return B();
}
};
int main()
{
B b = A(); //what should be called here? apparently, A::operator B()
return 0;
}
The above code displays "called A's conversion operator", meaning that the conversion operator is called as opposed to the constructor. If you remove/comment out the operator B() code from A, the compiler will happily switch over to using the constructor instead (with no other changes to the code).
My questions are:
Since the compiler doesn't consider B b = A(); to be an ambiguous call, there must be some type of precedence at work here. Where exactly is this precedence established? (a reference/quote from the C++ standard would be appreciated)
From an object-oriented philosophical standpoint, is this the way the code should behave? Who knows more about how an A object should become a B object, A or B? According to C++, the answer is A -- is there anything in object-oriented practice that suggests this should be the case? To me personally, it would make sense either way, so I'm interested to know how the choice was made.
Thanks in advance
| You do copy initialization, and the candidate functions that are considered to do the conversions in the conversion sequence are conversion functions and converting constructors. These are in your case
B(const A&)
operator B()
Now, that are the way you declare them. Overload resolution abstracts away from that, and transforms each candidate into a list of parameters that correspond to the arguments of the call. The parameters are
B(const A&)
B(A&)
The second one is because the conversion function is a member function. The A& is the so-called implicit object parameter that's generated when a candidate is a member function. Now, the argument has type A. When binding the implicit object parameter, a non-const reference can bind to an rvalue. So, another rule says that when you have two viable functions whose parameters are references, then the candidate having the fewest const qualification will win. That's why your conversion function wins. Try making operator B a const member function. You will notice an ambiguity.
From an object-oriented philosophical standpoint, is this the way the code should behave? Who knows more about how an A object should become a B object, A or B? According to C++, the answer is A -- is there anything in object-oriented practice that suggests this should be the case? To me personally, it would make sense either way, so I'm interested to know how the choice was made.
For the record, if you make the conversion function a const member function, then GCC will chose the constructor (so GCC seems to think that B has more business with it?). Switch to pedantic mode (-pedantic) to make it cause a diagnostic.
Standardese, 8.5/14
Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3).
And 13.3.1.4
Overload resolution is used to select the user-defined conversion to be invoked. Assuming that "cv1 T" is the type of the object being initialized, with T a class type, the candidate functions are selected as follows:
The converting constructors (12.3.1) of T are candidate functions.
When the type of the initializer expression is a class type "cv S", the conversion functions of S and its base classes are considered. Those that are not hidden within S and yield a type whose cv-unqualified version is the same type as T or is a derived class thereof are candidate functions. Conversion functions that return "reference to X" return lvalues of type X and are therefore considered to yield X for this process of selecting candidate functions.
In both cases, the argument list has one argument, which is the initializer expression. [Note: this argument will be compared against the first parameter of the constructors and against the implicit object parameter of the conversion functions. ]
And 13.3.3.2/3
Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if [...] S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.
|
1,384,119 | 1,388,020 | Help with translating this assembly into c | My compiler won't work with an assembly file I have and my other compiler that will won't work with the c files I have. I don't understand assembly. I need to move this over but I'm not getting anywhere fast. Is there someone out there that can help? I can't believe there isn't a translator available. Here is the beginning of the file:
list p=18F4480
#include <p18F4480.inc>
#define _Z STATUS,2
#define _C STATUS,0
GLOBAL AARGB0,AARGB1,AARGB2,AARGB3
GLOBAL BARGB0,BARGB1,BARGB2,BARGB3
GLOBAL ZARGB0,ZARGB1,ZARGB2
GLOBAL REMB0,REMB1
GLOBAL TEMP,TEMPB0,TEMPB1,TEMPB2,TEMPB3
GLOBAL LOOPCOUNT,AEXP,CARGB2
LSB equ 0
MSB equ 7
math_data UDATA
AARGB0 RES 1
AARGB1 RES 1
AARGB2 RES 1
AARGB3 RES 1
BARGB0 RES 1
BARGB1 RES 1
BARGB2 RES 1
BARGB3 RES 1
REMB0 RES 1
REMB1 RES 1
REMB2 RES 1
REMB3 RES 1
TEMP RES 1
TEMPB0 RES 1
TEMPB1 RES 1
TEMPB2 RES 1
TEMPB3 RES 1
ZARGB0 RES 1
ZARGB1 RES 1
ZARGB2 RES 1
CARGB2 RES 1
AEXP RES 1
LOOPCOUNT RES 1
math_code CODE
;---------------------------------------------------------------------
; 24-BIT ADDITION
_24_BitAdd
GLOBAL _24_BitAdd
movf BARGB2,w
addwf AARGB2,f
movf BARGB1,w
btfsc _C
incfsz BARGB1,w
addwf AARGB1,f
movf BARGB0,w
btfsc _C
incfsz BARGB0,w
addwf AARGB0,f
return
I get that I can largly exclude the first two lines as the device defines are in my main.c anyway. The two #defines are just that, but the simplest way (I think) is to just replace instances of _Z and _C with STATUS,2 and STATUS,0 accordingly. The next lines (the GLOBALs) are simply variable declarations I'm gathering. Same with LSB and MSB except they also assign values. The next chunck I think I just declare a bunch of integers with those names (AARGB0, etc) and then the chunck after that is a function.
I don't even bother to translate that function, because my compiler has #asm/#end asm directives so I can put it in raw (as long as its wrapped in a function).
I think I have it all... until I build and my compiler screams about STATUS not being defined. And of course its not. But what is it? I read on the net that STATUS registers are something special but I really don't get how it works.
If you haven't noticed, I'm not even sure what it is I'm really asking. I just want the bloody thing to work.
| STATUS is a built-in register in the PIC architecture, that implements the same functionality as the "status" or "condition" flags register in most larger CPU:s. It contains bitflags that are set and cleared by the microcontroller as it executes code, telling you the result of operations.
The Z flag, for instance, is set whenever an arithmetic operation results in a zero, and the C (carry) flag is set when arithmetic overflow is detected.
These are flags that are typically not visible from C, as C doesn't want to require that the host processor even has status bits, so directly translating this code to C will be hard. You will need to figure out a way to include the status-reading bit tests in the C code, and use those instructions when possible. This might be troublesome, as from C you have less control over which registers are being used, which in turn might make it hard to make sure you're checking the proper flags in the right place(s).
Here are a few links to other people's extended precision PIC code. Most seem to remain in assembly, but they might still be useful as references or inspiration.
|
1,384,125 | 20,020,321 | (C++) MessageBox for Linux like in MS Windows | I need to implement a simple graphical message box for a Linux (SDL) application similar to the Windows MessageBox in C++ (gcc/g++ 4.4.0). All it needs to do is to display a caption, a message and an ok or close button and to return to the calling function when that button is clicked.
SDL just uses X(11) to open a window for (OpenGL) rendering.
I have looked through a similar thread regarding a GTK implementation, but that implementation doesn't seem to work properly.
I have also tried wxWidgets' wxMessageBox function, but compiling the headers makes the compiler throw error messages about syntax errors in include/c++/4.4.0/bits/stl_algobase.h (gcc 4.4.0 32 bits on openSuSE 11.1 32 bits). Using wxWidgets also means having to link a ton of libraries, adding STL to my app (Which it doesn't need otherwise) and who knows what else, so I do not want to use wxWidgets.
X11/motif (openmotif) has what I need (XmCreate{Error|Warning|InfoDialog), but these need a parent widget (e.g. top level window) which I don't have and do not accept a NULL parameter for these.
So I am stumped right now. Is there a simple way to do what I want? Or at least a halfway simple/easy/straightforward one? If yes, which one (giving as many details as possible would be highly appreciated).
| In SDL2, you can now show message boxes:
http://wiki.libsdl.org/SDL_ShowSimpleMessageBox
int SDL_ShowSimpleMessageBox(Uint32 flags,
const char* title,
const char* message,
SDL_Window* window)
http://wiki.libsdl.org/SDL_ShowMessageBox
int SDL_ShowMessageBox(const SDL_MessageBoxData* messageboxdata,
int* buttonid)
|
1,384,326 | 1,385,031 | C++: Optimize using templates variables | Currently, I have some code as follows
template<typename Type>
Type* getValue(std::string name, bool tryUseGetter = true)
{
if(tryUseGetter)
{
if(_properties[name]->hasGetter)
{
return (Type*)_properties[name]->getter();
}
return (Type*)_properties[name]->data;
}
else
{
return (Type*)_properties[name]->data;
}
}
Is there a way to make tryUseGetter a compile time switch? i.e. move it to the template declaration so it's something akin to this
template<typename Type, bool tryUseGetter = true>
...
Thanks.
| You could use type cast operator and structure getValue as follows (usage syntax will be the same as with function) :
template<typename Type, bool tryUseGetter = true>
struct getValue {};
template<typename Type>
struct getValue<Type, true> {
getValue(const std::string& name) : name(name) {};
operator Type*() const {
if(_properties[name]->hasGetter) {
return (Type*)_properties[name]->getter();
}
return (Type*)_properties[name]->data;
}
private:
const std::string& name;
};
template<typename Type>
struct getValue<Type, false> {
getValue(const std::string& name) : name(name) {};
operator Type*() const {
return (Type*)_properties[name]->data;
}
private:
const std::string& name;
};
Usage:
int main () {
int* i = getValue<int>( "TEST" ); // true by default
Xstruct* x = getValue<Xstruct, false>( "XS" ); // false
}
|
1,384,348 | 1,384,352 | "rounding" with integers | I'm trying to get rid of floats in my functions.
I have one function that operates on a 16 bit integer value which is an upscaled 8 bit value. Then a downscaled 8 bit is sent to the output.
I'm sure I'm not explaining it well. Something like this:
int8 spot_value = 21; //arbitrary. just need a starting point
int16 running_value;
running_value = spot_value << 8; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = running_value >> 8; //downscale again
if we were working with floats my downscaled value would be 21.6 which I could round easily to 22 and convert to an int8. But as-is it will truncate to 21 which I don't want.
Is there a way to "round" the integer up if it would have been appropriate to do so had it been a float but without converting anything to a float (even temporarily)?
It is probably a lot simpler than I'm making it out to be.
| You could add 1/2 to the value. In your scaled system that's 128.
int8 spot_value = 21; //arbitrary. just need a starting point
int16 running_value;
running_value = spot_value << 8; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = running_value + 128; //add an additional 1/2 for rounding
spot_value = spot_value >> 8; //downscale again
or...
scale_shift = 8;
scale = 1 << scale_shift
round = scale >> 1;
int8 spot_value = 21; //arbitrary. just need a starting point
int16 running_value;
running_value = spot_value << scale_shift; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = (running_value + round) >> scale_shift; //downscale again
or a bit trick based on Dav's answer...
running_value = spot_value << scale_shift; //multiply by 256 which is 5376
running_value += 154; //my upscaled value is now 5530
spot_value = (running_value >> 8) + ((running_value >> 7) & 1)
.
|
1,384,409 | 1,384,420 | Visual Studio 2008 C++ language support? | I've been developing a couple of C# tools recently, but primarily working with a lot of legacy Visual Basic 6.0 code (I know, I know...). For the C# development, I've been using Visual Studio 2008 Professional edition that I downloaded using our MSDN subscription here at work.
But, as a change of pace over the weekend, I was going to check out a complex C++ project that we have. However, when I went to open it through Visual Studio, it wouldn't open it saying that the .vcproj file type wasn't supported. I figured it was a compatibility issue and that the project file type had changed between versions of Visual Studio, but when I tried creating a new C++ application inside Visual Studio 2008 Pro, the option just wasn't there.
I've been searching online by way of Bing, Google, MSDN, and MSDN subscriber downloads to no avail. Nothing I've found so far explains why this is happening.
I have found the express edition of MS Visual C++ 2008, but I could not locate the "full version" of this part of Visual Studio.
Any help would be much appreciated.
| It sounds like you haven't got it installed.
Go to Add/Remove Programs (or Programs and Features, or whatever Windows 7 calls it) and modify your installation. You'll get a list of checkboxes so you can install C#, VB.NET, Crystal Reports etc... and Visual C++. Check that checkbox and wait the hour or so for the installer to do its stuff.
|
1,384,458 | 1,559,385 | Developing custom list control in 5th edition | If a custom list control is to be developed for S60 5th edition phones, what is the best approach to do that?
The control should enable rich presentation of data in custom layouts. It should be possible to include images, texts, buttons in every item. Each list item should be able to expand/collapse to provide more details about the item, and the rest of the list should adapt to the display space that is left.
Do you know of any Symbian application that has a control similar to this?
As this control should be flexible as well, I have been thinking about using some UI layout that is configurable by XML. So far, I have come up with HTMLControl for Symbian. What else can you recommend? What's your best practice?
The UI is tightly linked to native code in C++, so I am not considering WRT.
| Subclassing listboxes in S60 (Avkon) is a major pain. I've done this a few times, more or less successfully, ususally less.
It is telling that Jan-Ole wrote his custom list box for Gravity, it probably spared him a lot of effort and made the UI experience better.
So either write something from scratch that just draws on the screen, or see if you can start using Qt already. It will be shipping in Symbian^3 onwards, and does install all the way back to S60 3rd edition.
|
1,384,946 | 1,384,951 | Force Preprocessor to use a previous definition in a redefinition | Update 3:
Never mind. I kinda got what I was looking for. The following gives unique identifiers inside a class.
static const int _counter_start = __COUNTER__;
static const int val1 = __COUNTER__ - _counter_start;
static const int val2 = __COUNTER__ - _counter_start;
Update 2:
Boost Preprocessor
I will be implementing something akin to a message map with this functionality.
class a
{
...
MAP_BEGIN()
MAP_DECL...
MAP_END()
...
};
The thing is, for each MAP_DECL, I need to expand the macro in 2 places.
class a
{
virtual void func()
{
...
//does something with the decl declaration
}
...
//also expand some stuff here
}
Boost preprocessor should (theoretically) allow me to accumulate MAP_DECL into a sequence and expand it into func() at the end (while simultaneously expanding the class fields as we go).
Update 1:
I'm using the Boost Preprocessor library at the moment. I'm currently stuck creating a new macro variable/definition like the following every time I need to add something to the sequence.
I'm trying to expand Boost Preprocessor sequences and I'm stuck doing this at the moment
#define SEQ (w)(x)(y)(z)
#define SEQ2 BOOST_PP_SEQ_PUSH_BACK(SEQ, a)
Original:
Suppose I have the following code
#define CUR 2
#define CUR CUR + 2
How do I force the 2nd line to use the value of CUR from the first line?
| Succinctly, you can't.
At the time when CUR is expanded (after the second #define), the preprocessor will replace an instance of CUR with CUR + 2, and 'blue paint' the name CUR (not expanding it any further). Thereafter, the C compiler sees CUR + 2, which most likely yields a compilation error.
|
1,385,709 | 1,385,777 | Cross-platform primitive data types in C++ | Unlike Java or C#, primitive data types in C++ can vary in size depending on the platform. For example, int is not guaranteed to be a 32-bit integer.
Various compiler environments define data types such as uint32 or dword for this purpose, but there seems to be no standard include file for fixed-size data types.
What is the recommended method to achieve maximum portability?
| I found this header particularly useful:
BOOST cstdint
Usually better than inventing own wheel (which incurs the maintenance and testing).
|
1,385,819 | 1,385,834 | Fill an ellipse in C++ | I'm trying to make a simple drawing app in c++, but i'm having trouble finding a function that fills an ellipse, all i have found is FillRect, could someone lead me in the right direction?
Thanks
| See Ellipse:
The Ellipse function draws an ellipse. The center of the ellipse is the center of the specified bounding rectangle. The ellipse is outlined by using the current pen and is filled by using the current brush.
|
1,385,890 | 1,385,991 | Reducing installation of libraries | I have a C++ project that have like 15+ external libraries installed with a package mananger. The problem is with the package change, the newest versions of some library break things (like libblob). I wanted to know if it exists a way to not relaying on some package manager for installing our library and to make sure we always have the version we want.
Thanks for your suggestion.
| If you don't want to use a package manager, then don't use a package manager.
apt is a great tool and is there to help, but you aren't required to use it.
On Ubuntu, you might want to just use dpkg instead of apt and so that none
of the dependencies will be automatically updated and avoid upgrading the
libraries that are causing problems. Or, just install everything directly
from source. If you go that route, install to /usr/local or some
non-standard location. (ie, do NOT configure --prefix=/usr &&
make && make install. Use the default /usr/local or $HOME for prefix.)
Note that doing this is a heinous kludge, and you have bigger problems. If you
are relying on libraries that are unstable, then you probably ought to consider
removing your dependency on those libraries. Also, mixing usage of dpkg with
apt will cause maintenance headaches. If you do that, only do it on your
developmental boxes (eg, not on production servers.) Your primary concern
should be to get your package working correctly with the package management
system, and one part of this may involve fixing the packaging of all the
libraries you depend on.
|
1,386,075 | 1,386,086 | Overloading operator [] for a sparse vector | I'm trying to create a "sparse" vector class in C++, like so:
template<typename V, V Default>
class SparseVector {
...
}
Internally, it will be represented by an std::map<int, V> (where V is the type of value stored). If an element is not present in the map, we will pretend that it is equal to the value Default from the template argument.
However, I'm having trouble overloading the subscript operator, []. I must overload the [] operator, because I'm passing objects from this class into a Boost function that expects [] to work correctly.
The const version is simple enough: check whether the index is in the map, return its value if so, or Default otherwise.
However, the non-const version requires me to return a reference, and that's where I run into trouble. If the value is only being read, I do not need (nor want) to add anything to the map; but if it's being written, I possibly need to put a new entry into the map. The problem is that the overloaded [] does not know whether a value is being read or written. It merely returns a reference.
Is there any way to solve this problem? Or perhaps to work around it?
| There may be some very simple trick, but otherwise I think operator[] only has to return something which can be assigned from V (and converted to V), not necessarily a V&. So I think you need to return some object with an overloaded operator=(const V&), which creates the entry in your sparse container.
You will have to check what the Boost function does with its template parameter, though - a user-defined conversion to V affects what conversion chains are possible, for example by preventing there being any more user-defined conversions in the same chain.
|
1,386,142 | 1,386,157 | Handling partial return from recv() TCP in C | I've been reading through Beej's Guide to Network Programming to get a handle on TCP connections. In one of the samples the client code for a simple TCP stream client looks like:
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("Client: received '%s'\n", buf);
close(sockfd);
I've set the buffer to be smaller than the total number of bytes that I'm sending. I'm not quite sure how I can get the other bytes. Do I have to loop over recv() until I receive '\0'?
*Note on the server side I'm also implementing his sendall() function, so it should actually be sending everything to the client.
See also 6.1. A Simple Stream Server in the guide.
| Yes, you will need multiple recv() calls, until you have all data.
To know when that is, using the return status from recv() is no good - it only tells you how many bytes you have received, not how many bytes are available, as some may still be in transit.
It is better if the data you receive somehow encodes the length of the total data. Read as many data until you know what the length is, then read until you have received length data. To do that, various approaches are possible; the common one is to make a buffer large enough to hold all data once you know what the length is.
Another approach is to use fixed-size buffers, and always try to receive min(missing, bufsize), decreasing missing after each recv().
|
1,386,183 | 1,386,390 | How to call a templated function if it exists, and something else otherwise? | I want to do something like
template <typename T>
void foo(const T& t) {
IF bar(t) would compile
bar(t);
ELSE
baz(t);
}
I thought that something using enable_if would do the job here, splitting up foo into two pieces, but I can't seem to work out the details. What's the simplest way of achieving this?
| There are two lookups that are done for the name bar. One is the unqualified lookup at the definition context of foo. The other is argument dependent lookup at each instantiation context (but the result of the lookup at each instantiation context is not allowed to change behavior between two different instantiation contexts).
To get the desired behavior, you could go and define a fallback function in a fallback namespace that returns some unique type
namespace fallback {
// sizeof > 1
struct flag { char c[2]; };
flag bar(...);
}
The bar function will be called if nothing else matches because the ellipsis has worst conversion cost. Now, include that candidates into your function by a using directive of fallback, so that fallback::bar is included as candidate into the call to bar.
Now, to see whether a call to bar resolves to your function, you will call it, and check whether the return type is flag. The return type of an otherwise chosen function could be void, so you have to do some comma operator tricks to get around that.
namespace fallback {
int operator,(flag, flag);
// map everything else to void
template<typename T>
void operator,(flag, T const&);
// sizeof 1
char operator,(int, flag);
}
If our function was selected then the comma operator invocation will return a reference to int. If not or if the selected function returned void, then the invocation returns void in turn. Then the next invocation with flag as second argument will return a type that has sizeof 1 if our fallback was selected, and a sizeof greater 1 (the built-in comma operator will be used because void is in the mix) if something else was selected.
We compare the sizeof and delegate to a struct.
template<bool>
struct foo_impl;
/* bar available */
template<>
struct foo_impl<true> {
template<typename T>
static void foo(T const &t) {
bar(t);
}
};
/* bar not available */
template<>
struct foo_impl<false> {
template<typename T>
static void foo(T const&) {
std::cout << "not available, calling baz...";
}
};
template <typename T>
void foo(const T& t) {
using namespace fallback;
foo_impl<sizeof (fallback::flag(), bar(t), fallback::flag()) != 1>
::foo(t);
}
This solution is ambiguous if the existing function has an ellipsis too. But that seems to be rather unlikely. Test using the fallback:
struct C { };
int main() {
// => "not available, calling baz..."
foo(C());
}
And if a candidate is found using argument dependent lookup
struct C { };
void bar(C) {
std::cout << "called!";
}
int main() {
// => "called!"
foo(C());
}
To test unqualified lookup at definition context, let's define the following function above foo_impl and foo (put the foo_impl template above foo, so they have both the same definition context)
void bar(double d) {
std::cout << "bar(double) called!";
}
// ... foo template ...
int main() {
// => "bar(double) called!"
foo(12);
}
|
1,386,319 | 1,389,157 | How to kill XtAppMainLoop (Motif)? | I want to use XmCreate{Error|Warning|Info}Dialog to display some message in screen in my SDL based application before its main window is open and any program data is available. I want the dialog to open, print the intended message, and when the user clicks on the OK button, the dialog plus the top widget I had to create for it should be closed/removed. Now afaik XtAppMainLoop will loop and process top widget messages (a window?) until the user closes it. I want to close it when the dialog returns though. How can I do that?
| After hours and hours of googling and reading I have found out that you can use XtAppSetExitFlag (XtAppContext).
|
1,386,674 | 3,027,284 | Syntax coloring of own types in Visual Studio (C++) | How can I get Visual Studio to highlight my own class types?
This works fine for C# but not for C++...
| For those running Visual Studio 2010 Highlighterr may fit your needs. It's also in the MSDN Visual Studio Gallery. It leverages the improved C++ IntelliSense in 2010.
It makes you set special highlighters in Environment -> Fonts and Colors for the types it detects, but overall it works quite well from what I've seen.
|
1,386,780 | 1,386,786 | What is the cleanest way to include and access binary data in VC++ Express? | I have some binary files that I'd like to embed in a dll I'm compiling with VC++ Express Edition.
I have a couple ways to do it (like converting the data to arrays that I compile along with the code), but I'm not satisfied and I feel like I'm probably missing an easy, straightforward solution.
What's the cleanest, easiest way to do this?
| I don't know if this is an option, but the Unix (and probably easily avaliable on Windows) program xxd has an option to output a C header:
xxd -i file.bin > file.h
file.h will contain the definition of an array of unsigned char containing the data and an unsigned int that tells you the length of the array. Of course, it may be better to output to file.c and then write file.h as:
extern unsigned char file[];
extern unsigned int file_len;
The names of the variables depend on the input file. Hope this helps.
|
1,387,095 | 1,388,073 | Learn C++ to understand examples in book fast, know C and Java already | I need to read "A Practical Introduction to Data Structures and Algorithm Analysis" by Shaffer for class but the code examples in the book are all in C++ which I do not know. I know C and Java already and was wondering if you knew any resources that helped learn enough C++ to understand these examples fast if you already know another language. Thanks!
| Another free textbook is The C++ Annotations by Frank B. Brokken. You can browse it online, or you can download the pdf version.
A quote from the first page:
This document is intended for
knowledgeable users of C (or any other
language using a C-like grammar, like
Perl or Java) who would like to know
more about, or make the transition to,
C++. This document is the main
textbook for Frank's C++ programming
courses, which are yearly organized at
the University of Groningen
What I like about "The C++ Annotations" is that is being kept uptodate, version 8.0.0 has
added C++0x chapters.
|
1,387,101 | 1,387,140 | C++ Class instance array initialization | I have a class A as follows:
class A
{
public:
A()
{
printf("A constructed\n");
}
~A();
//no other constructors/assignment operators
}
I have the following elsewhere
A * _a;
I initalize it with:
int count = ...
...
_a = new A[count];
and I access it with
int key = ....
...
A *a_inst = &(_a[key]);
....
It runs normally, and the printf in the constructor is executed, and all the fields in A are fine.
I ran Valgrind with the following args:
valgrind --leak-check=full --show-reachable=yes --track-origins=yes -v ./A_app
and Valgrind keeps yelling about
Conditional jump or move depends on uninitialised value(s)
and then the stack trace to the accessors statements.
Can anyone explain why this is happening? Specifically if what Valgrind says is true, why is the constructor executed?
| This can mean that key or count contains an uninitialized value. Even if you do initialize it in the declaration, e.g. int key = foo + bar;, it could be that either foo or bar is uninitialized, and valgrind carries this over to key.
|
1,387,206 | 1,487,332 | Using friends with base classes for Boost Parameter | I'm using the Boost Parameter tutorial to create a named-parameter constructor for a playing card generator. The tutorial says to put the ArgumentPack into a base class, but I want to modify variables in the card generator class. I've thought about doing this:
class CGconstructor_base {
public:
template<class ArgumentPack>
CGconstructor_base(ArgumentPack const& args);/*tutorial says to put code
in this function */
friend CardGenerator;//so it can modify the variables of CardGenerator
}
class CardGenerator:public CGconstructor_base;
Is this legal or is there a better way to manipulate the private variables in CardGenerator and use Boost Parameter library?
OS: Windows XP Pro, Compilier: Visual C++ 2008 Express,Boost: 1.39.0
| I think we need some cleanup.
the friend declaration seems ill-placed, from the comment you want CGconstructor_base to be able to access CardGenerator attributes: if this is so, then the friend declaration goes into CardGenerator (I say who I consider as my friends, you do not declare yourself as being someone I consider a friend).
Why do you need friend anyway ? It would be much better if as in the tutorial you used a structure and then stuffed the attributes into CGconstructor_base. This way you will be able to access them from CardGenerator naturally without this supplementary line. When you can do without the 'friend' keyword you should (usual caveat: if doing so does not increase the cost too much).
you want PRIVATE inheritance here, this is a detail implementation. Only use public inheritance (or protected even) when OTHER classes/methods will need to know use you 'as-a' base.
In a nutshell:
struct CGconstructor_base {
template<class ArgumentPack>
CGconstructor_base(ArgumentPack const& args);/*tutorial says to put code
in this function */
cg_type1 cg_attr1;
cg_type2 cg_attr2;
}; // don't forget this
class CardGenerator:private CGconstructor_base {};
I do wonder why 'inheritance' has been chosen by boost instead of (I think) cleaner composition. It is so much easier to abuse inheritance (and require Multiple-Inheritance)... I suppose it is worth a subject of its own though.
|
1,387,263 | 1,387,278 | C++: Hide base static member | In C++, is it possible to have a child class "hide" a base class' static fields and methods? (i.e. A has a field named ABC of type int, B:A and B has a field named ABC of type int)
| #include <iostream>
using namespace std;
class A{
public:
static int a;
};
class B: public A{
public:
static int a; // hide base member
};
int A::a;
int B::a;
int main(){
A::a=10;
B::a=20;
B k;
cout << "\n" << B::a << k.a;
return 0;
}
|
1,387,348 | 1,387,368 | What are efficient ways to debug an optimized C/C++ program? | Many times I work with optimized code (sometimes even involving vectorized loops), which contain bugs and such. How would one debug such code? I'm looking for any kind of tools or techniques. I use the following (possibly outdated) tools, so I'm looking to upgrade.
I use the following:
Since with ddd, you cannot see the code, I use gdb+ dissambler command and see the produced code; I can't really step through the program using this.
ndisasm
Thanks
| It is always harder to debug optimised programs, but there are always ways. Some additional tips:
Make a debug build, and see if you get the same bug in a debug build. No point debugging an optimised version if you don't have to.
Use valgrind if on a platform that supports it. The errors you see may be harder to understand, but catching the problem early often simplifies debugging.
printf debugging is primitive, but sometimes it is the simplest way if you have a complex issue that only shows up in optimised builds.
If you suspect a timing issue (especially in a multithreaded program), roll your own version of assert which aborts or prints if the condition is violated, and use it in a few select places, to rule out possible problems.
See if you can reproduce the problem without using -fomit-frame-pointers, since that makes code very hard to debug, and with -O2 or -O3 enabled. That might give you enough information to find the cause of your problem.
Isolate parts of your code, build a test-suite, and see if you can identify any testcases which fail. It is much easier to debug one function than the whole program.
Try turning off optimisations one by one with the -fno-X options. This might help you find common problems like strict aliasing problems.
Turn on more compiler warnings. Some things, like strict aliasing problems, can generate compiler warnings if they create a difference in behaviour between different optimisation levels.
|
1,387,460 | 1,399,123 | C++ Stack by Array Implementation | What I want to happen is for the pushFront(int) function to do this:
bool stack::pushFront( const int n )
{
items[++top] = n; // where top is the top of the stack
return true; // only return true when the push is successful
}
items is a struct type of the object "item". Have a look:
class stack
{
stack(int capacity);
~stack(void);
...
private:
int maxSize; // is for the item stack
int top; // is the top of the stack
struct item {
int n;
};
item *items;
i've defined the ctor to the stack class object and dtor as follows:
stack::stack(int capacity)
{
items = new item[capacity];
if ( items == NULL ) {
throw "Cannot Allocoate Sufficient Memmory";
exit(1);
}
maxSize = capacity;
top = -1;
}
stack::~stack(void)
{
delete [] items;
items = NULL;
maxSize = 0;
top = -1;
}
Yes the main issue for me is the items[++top] = n; statement. I've been trying to find ways around it like below:
bool stack::pushFront(const int n)
{
int *a = new int[maxSize];
a[++top] = n;
return true;
}
But I cant drag (+) 'a' array out to see those actual array elements... Which is what I was hoping to happen..
What I want is for the statement items[++top] = n; to work..
| bool stack::pushFront( const int n )
{
if(top == maxSize-1)
return false;
items[++top].n = n; // where top is the top of the stack
return true; // only return true when the push is successful
}
|
1,387,535 | 1,387,666 | C++: Convert Macro based Property System to use templates | I've already implemented, using macros, a C++ property system that satisfied the following requirements:
Property can be referenced using a integeral key
Property can be accessed via a generic Set/Get
Properties (and property keys) must be inheritable
Properties can be registered with getters/setters
and is implemented as follows
Each property belongs to a class
Each property is 'declared' with a key unique to it's inheritance chain. (Implemented using a rather clever __ COUNTER __ hack). It has the following characteristic
A root class (no parents) start numbering its properties from 0
A child class will start numbering its properties from the parent's last id + 1
class A
{
static const unsigned int Property_0 = GET_KEY_MACRO; //expands to 0
static const unsigned int Property_1 = GET_KEY_MACRO; //expands to 1
};
class B : public A
{
static const unsigned int Property_0 = GET_KEY_MACRO(A); //expands to 2
//and so forth
};
class C : public A
{
static const unsigned int Property_0 = GET_KEY_MACRO(A); //expands to 2. different inheritance chain
};
Other code can refer to the property using the static constant id.
objectinstance.SetValue(C::Property_0, 5)
Each property is 'registered' by using a macro that expands to a virtual method. The macro currently allows for a property type, a getter, and a setter to be registered
BEGIN_PROPERTIES
REG_PROP(Property_0, int)
REG_PROP_G(Property_1, int, getterFunc)
...
END_PROPERTIES
//expands to
virtual void registerProperties()
{
register(blah, blah, ...)
}
SetValue/GetValue that takes a property key and does some background magic to set/get it(already implemented)
Can anyone think of template based approach that's equivalent/simpler to the above system?
Note: This property system is to designed for remote RPCish calls as well as fast local access.
| This looks like a classic game property system so I'm going to recommend you read this Gamasutra article about a good system that doesn't require too much gunk around your code. Also have a look at boost.fusion and see if it can't help you.
What follows is my opinion and can be ignored for the sake of the question:
That said I'm not really sure what you'd gain by using templates. Is it just that "Macros Are Bad"?
Having worked with a bunch of these systems I've come to the conclusion that you're often solving the wrong problem by adding a property system. If you can, consider using a language like C# where properties are first-class language feature.
|
1,387,609 | 1,388,015 | How do I use a pointer to char from SWIG, in Perl? | I used SWIG to generate a Perl module for a C++ program. I have one function in the C++ code which returns a "char pointer". Now I dont know how to print or get the returned char pointer in Perl.
Sample C code:
char* result() {
return "i want to get this in perl";
}
I want to invoke this function "result" in Perl and print the string.
How to do that?
Regards,
Anandan
| Depending on the complexity of the C++ interface, it may be easier, faster, and more maintainable to skip SWIG and write the XS code yourself. XS&C++ is a bit of an arcane art. That's why there is Mattia Barbon's excellent ExtUtils::XSpp module on CPAN. It make wrapping C++ easy (and almost fun).
The ExtUtils::XSpp distribution includes a very simple (and contrived) example of a class that has a string (char*) and an integer member. Here's what the cut-down interface file could look like:
// This will be used to generate the XS MODULE line
%module{Object::WithIntAndString};
// Associate a perl class with a C++ class
%name{Object::WithIntAndString} class IntAndString
{
// can be called in Perl as Object::WithIntAndString->new( ... );
IntAndString();
// Object::WithIntAndString->newIntAndString( ... );
// %name can be used to assign methods a different name in Perl
%name{newIntAndString} IntAndString( const char* str, int arg );
// standard DESTROY method
~IntAndString();
// Will be available from Perl given that the types appear in the typemap
int GetInt();
const char* GetString ();
// SetValue is polymorphic. We want separate methods in Perl
%name{SetString} void SetValue( const char* arg = NULL );
%name{SetInt} void SetValue( int arg );
};
Note that this still requires a valid XS typemap. It's really simple, so I won't add it here, but you can find it in the example distribution linked above.
|
1,387,647 | 1,387,747 | Persistant references in STL Containers | When using C++ STL containers, under what conditions must reference values be accessed?
For example are any references invalidated after the next function call to the container?
{
std::vector<int> vector;
vector.push_back (1);
vector.push_back (2);
vector.push_back (3);
vector[0] = 10; //modifies 0'th element
int& ref = vector[0];
ref = 10; //modifies 0'th element
vector.push_back (4);
ref = 20; //modifies 0'th element???
vector.clear ();
ref = 30; //clearly obsurd
}
I understand that in most implementations of the stl this would work, but I'm interested in what the standard declaration requires.
--edit:
Im interested becuase I wanted to try out the STXXL (http://stxxl.sourceforge.net/) library for c++, but I realised that the references returned by the containers were not persistent over multiple reads, and hence not compatible without making changes (however superficial) to my existing stl code. An example:
{
std::vector<int> vector;
vector.push_back (1);
vector.push_back (2);
int& refA = vector[0];
int& refB = vector[1]; //refA is not gaurenteed to be valid anymore
}
I just wanted to know if this meant that STXXL containers where not 100% compatible, or indeed if I had been using STL containers in an unsafe/implementation dependant way the whole time.
| About inserting into vectors, the standard says in 23.2.4.3/1:
[insert()] causes reallocation if the
new size is greater than the old
capacity. If no reallocation happens,
all the iterators and references
before the insertion point remain
valid.
(Although this in fact this talks about insert(), Table 68 indicates that a.push_back(x) must be equivalent to a.insert(a.end(), x) for any vector a and value x.) This means that if you reserve() enough memory beforehand, then (and only then) iterators and references are guaranteed not to be invalidated when you insert() or push_back() more items.
Regarding removing items, 23.2.4.3/3 says:
[erase()] invalidates all the
iterators and references after the
point of the erase.
According to Table 68 and Table 67 respectively, pop_back() and clear() are equivalent to appropriate calls to erase().
|
1,387,769 | 2,069,565 | Create registry entry to associate file extension with application in C++ | I would like to know the cleanest way of registering a file extension with my C++ application so that when a data file associated with my program is double clicked, the application is opened and the filename is passed as a parameter to the application.
Currently, I do this through my wix installer, but there are some instances where the application will not be installed on ths user's computer, so I also need the option of creating the registry key through the application.
Additionally, will this also mean that if the application is removed, unused entries in the registry will be left lying around?
| Your basic overview of the process is found in this MSDN article. The key parts are at the bottom of the list:
Register the ProgID
A ProgID (essentially, the file type registry key) is what contains your important file type properties, such as icon, description, and context menu items including applications used when the file is double clicked. Many extensions may have the same file type. That mapping is done in the next step:
Register the file name extension for the file type
Here, you set a registry value for your extension, setting that extension's file type to the ProgID you created in the previous step.
The minimum amount of work required to get a file to open with your application is setting/creating two registry keys. In this example .reg file, I create a file type (blergcorp.blergapp.v1) and associate a file extension (.blerg) with it.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\blergcorp.blergapp.v1\shell\open\command]
@="c:\path\to\app.exe \"%1\""
[HKEY_CURRENT_USER\Software\Classes\.blerg]
@="blergcorp.blergapp.v1"
Now, you probably want to accomplish this programmatically. To be absolutely kosher, you could check for the existence of these keys, and change your program behavior accordingly, especially if you're assuming control of some common file extension. However, the goal can be accomplished by setting those two keys using the SetValue function.
I'm not positive of the exact C++ syntax, but in C# the syntax looks something like this:
Registry.SetValue(@"HKEY_CURRENT_USER\Software\Classes\blergcorp.blergapp.v1\shell\open\command", null, @"c:\path\to\app.exe \"%1\"");
Registry.SetValue(@"HKEY_CURRENT_USER\Software\Classes\.blerg", null, "blergcorp.blergapp.v1");
Of course you could manually open each sub key, manually create the ProgID and extension subkey, and then set the key value, but a nice thing about the SetValue function is that if the keys or values don't exist, they will automatically be created. Very handy.
Now, a quick word about which hive to use. Many file association examples online, including ones on MSDN, show these keys being set in HKEY_CLASSES_ROOT. I don't recommend doing this. That hive is a merged, virtual view of HKEY_LOCAL_MACHINE\Software\Classes (the system defaults) and HKEY_CURRENT_USER\Software\Classes (the per-user settings), and writes to any subkey in the hive are redirected to the same key in HKEY_LOCAL_MACHINE\Software\Classes. Now, there's no direct problem doing this, but you may run into this issue: If you write to HKCR (redirected to HKLM), and the user has specified the same keys with different values in HKCU, the HKCU values will take precedence. Therefore, your writes will succeed but you won't see any change, because HKEY_CURRENT_USER settings take precedence over HKEY_LOCAL_MACHINE settings.
Therefore, you should take this into consideration when designing your application. Now, on the flip side, you can write to only HKEY_CURRENT_USER, as my examples here show. However, that file association setting will only be loaded for the current user, and if your application has been installed for all users, your application won't launch when that other user opens the file in Windows.
That should be a decent primer for what you want to do. For further reading I suggest
Best Practices for File Association
File Types and File Association, especially
How File Associations Work
And see also my similar answer to a similar question:
Associating file extensions with a program
|
1,387,906 | 1,387,977 | C++ with Python embedding: crash if Python not installed | I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing.
I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes.
I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase.
A few hours ago, I tried the app on my laptop that has Python 2.6 installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails.
I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash.
I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it.
What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue.
Thank you very much in advance.
| In addition to pythonxy.dll, you also need the entire Python library, i.e. the contents of the lib folder, plus the extension modules, i.e. the contents of the DLLs folder. Without the standard library, Python won't even start, since it tries to find os.py (in 3.x; string.py in 2.x). On startup, it imports a number of modules, in particular site.py.
There are various locations where it searches for the standard library; in your cases, it eventually finds it in the registry. Before, uses the executable name (as set through Py_SetProgramName) trying to find the landmark; it also checks for a file python31.zip which should be a zipped copy of the standard library. It also checks for a environment variable PYTHONHOME.
You are free to strip the library from stuff that you don't need; there are various tools that compute dependencies statically (modulefinder in particular).
If you want to minimize the number of files, you can
link all extension modules statically into your pythonxy.dll, or even link pythonxy.dll statically into your application
use the freeze tool; this will allow linking the byte code of the standard library into your pythonxy.dll.
(alternatively to 2.) use pythonxy.zip for the standard library.
|
1,388,065 | 1,388,085 | How to effectively delete C++ objects stored in multiple containers? auto_ptr? | I have an application which creates objects of a certain kind (let's say, of "Foo" class) during execution, to track some statistics, and insert them into one or both of two STL maps, say:
map<Foo*, int> map1;
map<Foo*, int> map2;
I was wondering what is the best way to delete the Foo objects. At the moment my solution is to iterate over map1 and map2, and put the Foo pointers into a set, then interating on this set and call delete on each.
Is there a more effective way, possibly using auto_ptr? If so how, since auto_ptr<> objects can't be stored in STL containers?
Thanks in advance.
| auto_ptr objects cannot, as you say, be stored in STL containers. I like to use the shared_ptr object (from boost) for this purpose. It is a referenced counted pointer, so the object will be deleted once only, when it goes out of scope.
typedef<shared_ptr<Foo>, int> Map;
Map map1;
Map map2;
Now, you just add and remove from map1 and map2, shared_ptr objects as they were pointers, and they will take care of the deletion, when the last reference is removed.
|
1,388,136 | 1,388,158 | Generating HTML (i.e. br and p tags) from plaintext in C++ | I've got a bunch of text like this:
foo
bar
baz
What's likely to be the most efficient way in C++ of transforming that to this:
<p>foo<br />bar</p>
<p>baz</p>
for large(ish) quantities of text (up to 8000 characters).
I'm happy to use boost's regex_replace, but I was wondering if string searching for \n\n might be more efficient? Any thoughts? Any other approaches?
Most third-party libraries are not available to me in the environment I'm working in.
| I would use a simple state-machine. It does require
comparison of the state for each time through the loop, but
it should not matter (it could be optimised by having a sub
loop in the third state - see below). The start state would
be the same as when two newlines have be encountered. There
would be a variable for the previous character and one for
keeping track of the position of the last newline (used for
generating output).
The states would be:
encountered double new line. Action when enter into state: output of <p>, the line and </p>
encountered single new line. Action when enter into state: output of the line and
encountered normal character
The program would look more like a C-program, though...
|
1,388,230 | 1,391,665 | VC6 and template error | I am overloading operator << to implement a stream like interface for a class:
template<typename T>
CAudit& operator << ( const T& data ) {
audittext << data;
return *this;
}
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
The template version fails to compile with "fatal error C1001: INTERNAL COMPILER ERROR (compiler file 'msc1.cpp', line 1794)". Non-template functions all compile correctly.
Is this due to VC6s deficiencies when handling templates and is there a way around this?
Thanks,
Patrick
EDIT :
the full class is:
class CAudit
{
public:
/* TODO_DEBUG : doesn't build!
template<typename T>
CAudit& operator << ( const T& data ) {
audittext << data;
return *this;
}*/
~CAudit() { write(); }//If anything available to audit write it here
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
//overload the << operator to allow function ptrs on rhs, allows "audit << data << CAudit::write;"
CAudit& operator << (CAudit & (*func)(CAudit &))
{
return func(*this);
}
void write() {
}
//write() is a manipulator type func, "audit << data << CAudit::write;" will call this function
static CAudit& write(CAudit& audit) {
audit.write();
return audit;
}
private:
std::stringstream audittext;
};
The problem occurs with the function overload of operator << which is used to allow write() to be used as a stream manipulator:
CAudit audit
audit << "Billy" << write;
| That overload of the template for function pointers surely is too much for good old Visual Studio 6.
As a workaround you could define a type for your manipulator and overload operator<< for that type.
Here's some code:
#include "stdafx.h"
#include <string>
#include <iostream>
#include <sstream>
#include <windows.h>
class CAudit {
std::ostringstream audittext;
void do_write() {}
public:
~CAudit() { do_write(); }
// types for manipulators
struct Twrite {};
// manipulators
static Twrite write;
// implementations of <<
template<typename T>
CAudit& operator << ( const T& data ) {
audittext << data;
return *this;
}
CAudit& operator << ( LPCSTR data ) {
audittext << data;
return *this;
}
CAudit& operator << ( Twrite& ) {
do_write();
return *this;
}
};
// static member initialization
CAudit::Twrite CAudit::write;
int main(int argc, char* argv[])
{
CAudit a;
int i = 123;
const char * s = "abc";
a << i << s << CAudit::write;
return 0;
}
|
1,388,469 | 1,388,493 | Is there a working C++ refactoring tool? | Does anybody know a fully featured refactoring tool for C++ that works reliably with large code bases (some 100.000 lines)?
I tried whatever i can find again and again over the last years: SlickEdit, Eclipse CDT. They all were not at all usable.
SUMMARY:
I took time and evaluated "Visual Assist X" as well as "Refactor for C++". Both have some impressing features, but both as well are far from perfect. Extracting a large block of code usually is not done satisfying without manual modifications - and therefore does not pay off.
"Visual Assist X" has nice features such as much more complete autocompletition etc. But it leads to so much flickering and slows down much at certain points.
By my opinion therefore the answer is: "No, there is no production ready refactoring tool for C++"
UPDATE March 2015
As for hdoghmens reply today i tried Resharper for C++.
His link
https://www.jetbrains.com/resharper/ does not say anything about C++. But i found Resharper C++ that was announced more than a year ago here:
https://www.jetbrains.com/resharper/features/cpp.html
I gave it a try with VC2010 using a code base of 20MB.
Test 1: Extract Method:
results in a Resharper exception. No source code changed.
Test 2: Extract Method with different source:
Works fine
Test 3: Change signature of extracted function: Results in broken C++ code:
bool myclass::do_work123(<unknown long Color>int& Filled*&, long, int&)
Maybe thats why C++ its not listed on the main page.
By my opinion the answer to this question still is "NO".
| I find Visual Assist X with Visual Studio very useful. Another choice is Refactor for C++.
|
1,388,597 | 1,388,642 | std::vector and c-style arrays | I am experimenting with OpenCL to increase the speed of our software. We work with maps a lot and, to simplify, represent a map as a std::vector< std::vector >. The OpenCL API takes raw c-style pointers as arguments, for example int* in the case above.
My questions:
Are there implementation guarantees in the stl that vector is, internally, consecutive in memory?
Can I safely cast a std::vector to int* and expect that to work?
In the case of a vector of vectors, can I still assume this holds true? I would expect the vector to hold other state data, or alignment issues, or maybe something else...
What is the best way to approach this? Write a custom 2d data structure that holds an internal, contiguous-in-memory buffer and work with that? I'd have to copy to/from vectors a lot...
Thanks.
|
Are there implementation guarantees in the stl that vector is, internally, consecutive in memory?
As of C++03, yes, a vector is guaranteed to use contiguous storage.
(In C++98, there was an accidental loophole so an implementation could hypothetically use non-contiguous storage, but it was fixed in the 2003 revision of the standard - and no implementation actually used non-contiguous storage because it'd be a terrible idea)
Can I safely cast a std::vector to int* and expect that to work?
The usual way is &v[0]. (&*v.begin() would probably work too, but I seem to recall there's some fluffy wording in the standard that makes this not 100% reliable)
No. Why would you expect that to work? A vector is a class. It is not a pointer. It just contains a pointer.
In the case of a vector of vectors, can I still assume this holds true? I would expect the vector to hold other state data, or alignment issues, or maybe something else...
The vector behaves the same whatever you store in it. If you make a vector of vectors, you end up with an object which contains a pointer to a heap-allocated array, where each element is an object which contains a pointer to a heap-allocated array.
As for how you should approach this, it depends on a lot of factors. How big is your total dataset? You might want to have the entire table allocated contiguously. With a vector of vectors, each row is a separate allocation.
|
1,388,608 | 1,388,670 | How to work around Visual Studio Compiler crashes | We have a large Visual Studio 2005 C++/Mfc solution, 1 project with around 1300 source files (so about 650 .h and 650 .cpp files). We also use Boost and a few other libraries (COM: MSXML, Office).
Recently, I've added a few instances of boost::multi_index to speed up things a bit. This all compiles most of the time. But now, when I'm doing a full (release) rebuild, I get compiler crashes at a few modules.
Fatal Error C1060: "compiler is out of heap space"
I've already tried to reduce includes in the precompiled header file (removed pretty much everything except the standard MFC headers). Also, I've removed the compiler option /Zm200 (which we needed before to compile the precompiled header file).
The strange thing: when I just press F7 (build) after the compiler crashes, the build process continues without any problems (or at least up to the next compiler crash, where I press F7 again). But it would be nice to be able to do a complete build without any breaks.
Can I influence the build order of the individual modules? This way, I could put the "problematic" modules at the beginning of the process (and hope the crashes don't just shift to other modules).
BTW: A complete build takes around 90 minutes.
Update:
Thanks for the answers. I was able to get rid of the compiler crashes and reduce compile time significantly. Here's what I did:
I removed all the includes from the precompiled header file, just the standard windows/mfc headers were left as they were. This forced me to add even more includes into other modules, but in the end everything was included where it was needed. Of course, this step increased compile time, but allowed me to be more efficient in the next step.
I installed the trial version of ProFactors IncludeManager. The Project Detail View can be exported to Excel, where bottlenecks and candidates to be included in the precompiled header file can be spotted quite fast.
Most compile time was wasted with a few header files that included a heap of other header files (that included some more...). I had to use forward declarations to get rid of some nasty dependencies. Also, I moved some classes / functions out of critical headers into their own modules.
What to put in precompiled header? (MSVC) helped me getting the includes in the precompiled header file right. I've added STL, Boost, Windows headers. then added our own (more or less stable, optimized) headers, plus the resource header file.
I repeated steps 3 and 4 a few times, always checking with IncludeManager for new candidates.
Steps 1 to 5 brought compilation time (release mode) down, from 90 to about 45 minutes.
I disabled generation of Browse Information for everything, since we do not seem to use it (and I could not find any information for what it is really good for...). This cut off another 6 minutes of the build process.
I added the /MP (multi processor support) switch to the C++ compiler command. Now the rebuild time was down to 22 minutes. This was all done on a single core PC.
I moved the whole solution to a dual core PC. Rebuilding the project takes 16 minutes there.
Creating a debug build is 5 minutes faster:
17 minutes on the single core machine,
11 minutes on the dual core machine.
Update 2:
Above, where I mention "single core machine", actually a slower dual core machine is meant.
| If 1300 files are taking THAT long to compile then you are including waaaay too many header files that are unncecessary. I'd guess people have cut and pasted a bunch of headre files into a CPP file without thinking which headers they actually need so that loads of them are getting included when they ought not to be. I'm also guessing that you aren't forward declaring classes where you should be.
I'd suggest you need to spend some time going through your project and removing unnecessary #includes. I suspect this will fix your out of memory problems AND will improve your compile time.
|
1,388,685 | 1,388,752 | Local variable scope question | Why is the following code prints "xxY"? Shouldn't local variables live in the scope of whole function? Can I use such behavior or this will be changed in future C++ standard?
I thought that according to C++ Standard 3.3.2 "A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region."
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass( int ) { cout << "x" << endl; };
~MyClass() { cout << "x" << endl; };
};
int main(int argc,char* argv[])
{
MyClass (12345);
// changing it to the following will change the behavior
//MyClass m(12345);
cout << "Y" << endl;
return 0;
}
Based on the responses I can assume that MyClass(12345); is the expression (and scope). That is make sense. So I expect that the following code will print "xYx" always:
MyClass (12345), cout << "Y" << endl;
And it is allowed to make such replacement:
// this much strings with explicit scope
{
boost::scoped_lock lock(my_mutex);
int x = some_func(); // should be protected in multi-threaded program
}
// mutex released here
//
// I can replace with the following one string:
int x = boost::scoped_lock (my_mutex), some_func(); // still multi-thread safe
// mutex released here
| You quoted standard correctly. Let me emphasize:
A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region.
You didn't declare any name, actually. Your line
MyClass (12345);
does not even contain a declaration! What it contains is an expression that creates an instance of MyClass, computes the expression (however, in this particular case there's nothing to compute), and casts its result to void, and destroys the objects created there.
A less confusing thing would sound like
call_a_function(MyClass(12345));
You saw it many times and know how it works, don't you?
|
1,389,082 | 1,390,016 | IPv6 address validation and canonicalization | What libs have you used for that? How compatible are they with one another? Or did you write your own parsing routine?
I'm particularly interested in mutually-compatible implementations for Java, C++, Python, and JavaScript, which support:
zero compression ("::")
IPv4-mapped addresses ("::ffff:123.45.67.89")
canonicalization (including to the short form, for human readability)
CIDR-style netmasks (like "/64" at the end)
| On POSIX systems you can use inet_pton and inet_ntop in combination to do canonicalization. You will still have to do your own CIDR parsing. Fortunately, I believe the only valid CIDR syntax for IPv6 is the /number_of_bits notation, so that's fairly easy.
The other issue you will run into is the lack of support for interface specifications. For link-local addresses, you will see things like %eth0 on the end to specify what link they are local too. getaddrinfo will parse that but inet_pton won't.
One strategy you could go for is using getaddrinfo to parse and inet_ntop to canonicalize.
getaddrinfo is available for Windows. inet_pton and inet_ntop aren't. Fortunately, it isn't too hard to write code to produce a canonical form IPv6 address. It will require two passes though because the rule for 0 compression is the biggest string of 0s that occurs first. Also IPv4 form (i.e. ::127.0.0.1) is only used for ::IPv4 or ::ffff:IPv4.
I have no Windows machine to test with, but from the documentation it appears that Python on Windows supports inet_pton and inet_ntop in its socket module.
Writing your own routine for producing a canonical form might not be a bad idea, since even if your canonical form isn't the same as everybody else's, as long as it's valid other people can parse it. But I would under no circumstances write a routine of your own to parse IPv6 addresses.
My advice above is good for Python, C, and C++. I know little or nothing about how to solve this problem in Java or Javascript.
EDIT: I have been examining getaddrinfo and its counterpart, getnameinfo. These are in almost all ways better than inet_pton and inet_ntop. They are thread safe, and you can pass them options (AI_NUMERICHOST in getaddrinfo's case, and NI_NUMERCHOST in getnameinfo's case) to keep them from doing any kind of DNS queries. Their interface is a little complex and reminds me of an ugly Windows interface in some respects, but it's fairly easy to figure out what options to pass to get what you want. I heartily recommend them both.
|
1,389,167 | 1,393,776 | Motif main window w/o system menu, minimize and maximize boxes how? (C++) | How do I create a Motif main window that doesn't have a system menu, minimize and maximize boxes? I just cannot find out how by googling and reading docs and tutorials. I believe that it should be possible with some additional parameters for XtVaCreateManagedWindow, but which?
I have tried several variants of XtVaSetValues (topWid, XmNmwmDecorations, ...) but none worked. Instead I get an error message that I need to use a vendor shell for this. Most widget types aren't derived from vendor shells however, and when I e.g. try to use a dialog shell and put a scrollable text widget inside of it, then then text widget seems to control the dialog.
| Apparently it's not (easily) possible to get rid of the window (system) menu, but it seems to be possible to disable window menu items with some code like this:
int i;
XtVaGetValues (widget, XmNmwmFunctions, &i);
i &= ~(MWM_FUNC_ALL | MWM_FUNC_MINIMIZE | MWM_FUNC_MAXIMIZE | MWM_FUNC_CLOSE);
XtVaSetValues (widget, XmNmwmFunctions, i);
which removes the related window decoration too and apparently even works for non vendor shell widgets.
|
1,389,337 | 1,389,403 | Singletons via static instance in C++ -- into source or into header files? | Cheers,
I ran into this chunk of code in "Programming Game AI by Example":
/* ------------------ MyClass.h -------------------- */
#ifndef MY_SINGLETON
#define MY_SINGLETON
class MyClass
{
private:
// member data
int m_iNum;
//constructor is private
MyClass(){}
//copy ctor and assignment should be private
MyClass(const MyClass &);
MyClass& operator=(const MyClass &);
public:
//strictly speaking, the destructor of a singleton should be private but some
//compilers have problems with this so I've left them as public in all the
//examples in this book
~MyClass();
//methods
int GetVal()const{return m_iNum;}
static MyClass* Instance();
};
#endif
/* -------------------- MyClass.cpp ------------------- */
//this must reside in the cpp file; otherwise, an instance will be created
//for every file in which the header is included
MyClass* MyClass::Instance()
{
static MyClass instance;
return &instance;
}
I am confused by the matter-of-fact statement by the author that the statically declared variable inside a function in header would result in declaring multiple, separate static variables instance. I don't think I've seen this behavior in my usual implementations of getInstance() function which I regularly put into headers (except that I like playing with pointers and initializing the singleton upon first use). I'm using GCC for my work.
So what does the standard say? What do non-compliant compilers say? Is the author's statement correct, and if so, can you name some compilers which would create multiple instances if getInstance() were declared in headers?
| In C++ nothing prevent an inline function to have a static variable and the compiler has to arrange to make that variable common between all translation units (like it has to do it for template instantiation static class members and static function variables). 7.1.2/4
A static variable in an extern inline function always refer to the same object.
Note that in C, inline functions can't have static variables (nor reference to object with internal linkage).
|
1,389,402 | 1,389,492 | std c++ container element destruction and insertion behaviour | I have made the following little Program:
(basically a class that couts if it gets created, copied or destroyed and a main that does some of that)
class Foo
{
public:
Foo(string name): _name(name)
{
cout << "Instance " << _name << " of Foo created!" << std::endl;
};
Foo(const Foo& other): _name(other._name)
{
cout << "Instance " << _name << " of Foo copied!" << std::endl;
};
~Foo()
{
cout << "Instance " << _name << " of Foo destroyed!" << std::endl;
}
string _name;
};
int main( int argc, char**argv)
{
Foo albert("Albert");
Foo bert("Bert");
{
vector<Foo> v1, v2;
system("PAUSE");
v1.push_back(albert);
system("PAUSE");
v2.push_back(bert);
system("PAUSE");
v1 = v2;
system("PAUSE");
}
system("PAUSE");
}
The output looks like this:
Instance Albert of class Foo created!
Instance Bert of class Foo created!
Press any key...
Instance Albert of class Foo copied!
Instance Albert of class Foo copied! // why another copy?
Instance Albert of class Foo destroyed! // and destruction?
Press any key...
Instance Bert of class Foo copied!
Instance Bert of class Foo copied!
Instance Bert of class Foo destroyed!
Press any key... // v1=v2 why did the albert instance not get destroyed?
Press any key...
Instance Bert of class A destroyed!
Instance Bert of class A destroyed!
Press any key... // there's still an albert living in the void
This strikes me as very odd.
Why do I even bother passing something as a reference if it gets copied twice anyway?
Why does the v1.operator=(other) not destroy the elements it contains?
It would fit nicely with the behaviour of shared_ptr.
Can someone tell me why?
ADDITION
I put this in an endless loop and checked the mem usage, it doesn't seem to produce
a mem leak at least.
ADDITION
Ok, the mem is not an issue because it uses operator= rather than the copy ctor, ok thanks.
When I add
v1.reserve(10);
v2.reserve(10);
the logical number of copies takes place. without that it reallocates and copies the whole vector for every single push_back, (which I find quite retarded even for small vectors).
Looking at this I will consider using .reserve more and optimize my assignment operators Like hell :)
ADDITION: SUMMARY
All these issues seem specific to VC++2005.
If the size of the two containers match, my implementation uses operator= on the
elements instead of destroying the old ones and copying the new ones, which seems
sound practice. IF the sizes differ, normal destruction and copying are used.
With the 2005 Implementation, one has to use reserve! Otherwise abysmal and not std compliant performance.
These black boxes are much blacker than I thought.
|
Why do I even bother passing something as a reference if it gets copied twice anyway?
You should consider STL container types as blackbox that can copy the objects you store as often as they need to. For instance, every time the container is resized, all of the objects will be copied.
It is possible that your compiler's implementation of push_back() uses a temporary extra copy. On my machine (gcc on Mac OS X), there are no extra copies during push_back() (according to your program's output).
This copy happens somewhere in the STL code, not in your copy constructor (since it uses a reference).
Why does the v1.operator=(other) not destroy the elements it contains?
Foo::operator= will be called for the "albert" instance with the "bert" instance as argument. Therefore, there is no implicit destroy and copy operation here. You might want to verify this by providing your own implementation for the operator:
Foo& operator=(const Foo& other) {
cout << "Instance " << other._name << " of Foo assigned to " << _name << "!" << std::endl;
return *this;
}
This produces the following output on my machine:
Instance Albert of Foo created!
Instance Bert of Foo created!
Instance Albert of Foo copied!
Instance Bert of Foo copied!
Instance Bert of Foo assigned to Albert!
Instance Bert of Foo destroyed!
Instance Albert of Foo destroyed!
Instance Bert of Foo destroyed!
Instance Albert of Foo destroyed!
|
1,389,414 | 1,389,766 | Motif: Intercept close box event and prevent application exit? (C++) | How do I intercept when the user clicks on a motif window's (widget's) close box, and how do I prevent the Motif window manager to close the entire calling application on the close box being clicked (so that my app can close the Motif application context and windows and continue to run)? I've tried to find out myself with Google, tuts and docs, but no dice. C++ required.
| This seems to work (found on the inet):
#include <Xm/Protocols.h>
Boolean SetCloseCallBack (Widget shell, void (*callback) (Widget, XtPointer, XtPointer))
{
extern Atom XmInternAtom (Display *, char *, Boolean);
if (!shell)
return False;
Display* disp = XtDisplay (shell);
if (!disp)
return False;
// Retrieve Window Manager Protocol Property
Atom prop = XmInternAtom (disp, const_cast<char*>("WM_PROTOCOLS"), False);
if (!prop)
return False;
// Retrieve Window Manager Delete Window Property
Atom prot = XmInternAtom (disp, const_cast<char*>("WM_DELETE_WINDOW"), True);
if (!prot)
return False;
// Ensure that Shell has the Delete Window Property
// NB: Necessary since some Window managers are not
// Fully XWM Compilant (olwm for instance is not)
XmAddProtocols (shell, prop, &prot, 1);
// Now add our callback into the Protocol Callback List
XmAddProtocolCallback (shell, prop, prot, callback, NULL);
return True;
}
Setting such a callback will prevent the application being closed as a result of the close event being handle be the default event handlers.
|
1,389,538 | 1,389,813 | Cancelling std::cout code lines using preprocessor | One can remove all calls to printf() using #define printf. What if I have a lot of debug prints like std::cout << x << endl; ? How can I quickly switch off cout << statements in a single file using preprocessor?
| NullStream can be a good solution if you are looking for something quick that removes debug statements. However I would recommend creating your own class for debugging, that can be expanded as needed when more debug functionality is required:
class MyDebug
{
std::ostream & stream;
public:
MyDebug(std::ostream & s) : stream(s) {}
#ifdef NDEBUG
template<typename T>
MyDebug & operator<<(T& item)
{
stream << item;
return *this;
}
#else
template<typename T>
MyDebug & operator<<(T&)
{
return *this;
}
#endif
};
This is a simple setup that can do what you want initially, plus it has the added benefit of letting you add functionality such as debug levels etc..
Update:
Now since manipulators are implemented as functions, if you want to accept manipulators as well (endl) you can add:
MyDebug & operator<<(std::ostream & (*pf)(std::ostream&))
{
stream << pf;
return *this;
}
And for all manipulator types (So that you don't have to overload for all manipulator types):
template<typename R, typename P>
MyDebug & operator<<(R & (*pf)(P &))
{
stream << pf;
return *this;
}
Be careful with this last one, because that will also accept regular functions pointers.
|
1,389,680 | 1,389,689 | Why is Qt looking for my slot in the base class instead of derived one? | I have my class X which inherits from Qt's class Base. I declared and defined void mySlot() slot in my class X and I'm connecting some signal to this slot in X's constructor. However, when running my program I get an error message saying there's no such slot as void mySlot() in the class Base.
Why is the code generated by Meta Object Compiler (moc) looking for my slot in the base class and not in my (derived) class?
| Did you add the Q_OBJECT macro on the derived class?
|
1,389,838 | 1,391,012 | How to debug macros efficiently in VS? | I've got a pretty complicated macro inside my (unmanaged) C++ code. Is there any way to expand macros in VS debugger? Or maybe there is another way to debug macros there?
F.e. I'd like to place a breakpoint inside it.
(Yes, I know macros are bad.)
| Go to either project or source file properties by right-clicking and going to "Properties". Under Configuration Properties->C/C++->Preprocessor, set "Generate Preprocessed File" to either with or without line numbers, whichever you prefer. This will show what your macro expands to in context. If you need to debug it on live compiled code, just cut and paste that, and put it in place of your macro while debugging.
|
1,389,899 | 1,389,906 | C++ Copy Constructor Syntax | I apologize in advance, my C++ is rusty...
What does
: m_nSize(sizeof(t1))
mean in the following section?
class CTypeSize
{
public:
template<class T>
CTypeSize(const T &t1) :
m_nSize(sizeof(t1))
{
}
~CTypeSize(void){ };
int getSize(void) const{ return m_nSize; }
private:
const int m_nSize;
};
I understand copy constructors, but I remember the syntax as Class::Class(const Class& p). Am I thinking of something else, or is that an alternative syntax?
Thanks!
| It has nothing todo with copy ctor. You are initializing the variable m_nSize using initializer list with the sizeof the template argument t1.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.