question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,117,654 | 3,119,638 | Update Qt4 statusbar from glwidget | I've got a window containing a QGLWidget and a QStatusBar. I calculate the fps inside a timerEvent call, but I don't know the 'correct' way to update the statusbar on every frame. fps is a member variable of GLWidget:
void GLWidget::timerEvent(QTimerEvent* event){
updateGL();
// Calculate FPS.
prevTime = currentTime;
currentTime = runTime.elapsed();
int timeDiff = currentTime - prevTime;
fps = 1000.0/timeDiff;
// Update statusbar with fps here.
}
Thanks!
| What you probably want is a custom signal on the GLWidget that you connect to a slot. Make the connection on the widget containing both the GLWidget and the status bar:
connect(&glWidgetInstance, SIGNAL(updateFPSSignal(int)), this, SLOT(updateFPSSlot(int)));
The slot function would look something like this:
void updateFPSSlot(int fps) {
// Update status bar
}
Note that if the status bar is a custom class, you can create the slot function in that class, and connect directly to it. Either way, the connection should be made within the class that contains the instances for both the GLWidget and the status bar.
|
3,117,848 | 3,118,453 | How is called a C/C++ program without end? | I mean a program based on events, a "static" program that don't just do a task but waits for events, etc. and doesn't end until the user manually close it.
EDIT: I have answered below, for example the programs we use every day and are based in Windows, like Microsoft Word, Firefox, etc. What is this type of program called? How is it possible to do something like that?
EDIT 2: I was going to reply individually some answers, but I will better reply here.
The program I want to do is something like a spider that works in a VPS as a daemon. When it starts it should look if there are tasks to do. If so it will generate the necessary threads (It's also thread based), so the main function needs an infinite loop based on events.
| Simply put, it's called an "Event-driven Program".
|
3,118,039 | 3,118,514 | typeid result across different dll's | I have two dlls which both declare a templated type, let's call A.
If the declaration of A is sufficiently intricate, it happens that
the result of typeid(A).name() is different when called in functions in two different
dll's.
example:
DLL1:
struct MyType: public A< TEMPLATE_LIST_OF_A >{}
void f(){
std::string name1 = typeid(A).name();
}
DLL2:
struct MyType: public A< TEMPLATE_LIST_OF_A >{}
void f(){
std::string name2 = typeid(A).name();
}
for example name1 could be something like: "???MyType??? etc"
while name2 could be "???A??TEMPLATE_LIST_OF_A etc".
Which actually makes quite sense to me, but is there is a way, provided that the
names used are the samem to guarantee that name1==name2 ?
thanks,
rob
| Not only is there no way to guarantee that typeid().name() is the same in different DLLs, the standard makes almost no guarantees about the string returned at all. Specifically, it is not guaranteed to be a) meaningful, b) unique for different types, c) the same for identical types.
As a quality of implementation issue, you can probably assume that these three conditions hold, but especially for complicated template types I wouldn't be surprised if you could find cases where they were violated in a specific compiler.
The relevant parts of the 98 standard are 5.2.8 and 18.5.1
|
3,118,165 | 3,118,188 | When do I use fabs and when is it sufficient to use std::abs? | I assume that abs and fabs are behaving different when using math.h. But when I use just cmath and std::abs, do I have to use std::fabs or fabs? Or isn't this defined?
| In C++, it's always sufficient to use std::abs; it's overloaded for all the numerical types.
In C, abs only works on integers, and you need fabs for floating point values. These are available in C++ (along with all of the C library), but there's no need to use them.
|
3,118,300 | 3,118,672 | How to get Driver Name? | how can I get the driver's name of a device to use with CreateFile?
handle = CreateFile( DRIVER_NAME_HERE,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
thanks!
| It's depend on what you want. A typical examples are
\\.\C:
\\.\Tcp
\\.\PhysicalDrive0
\\?\usbstor#disk&ven_sandisk&prod_cruzer&rev_8.01#1740030578903736&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
\\.\CON
(see http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx). I recommend you to also to use WinObj (see http://technet.microsoft.com/en-us/sysinternals/bb896657.aspx) to understand more about which devices you can use. If you start WinObj.exe and choose GLOBAL?? namespace you will see different names which can you use after \\.\ prefix. The function QueryDosDevice can be also helpful.
You can use DefineDosDevice function to create additional Symbolic link from \Device\Blabla to a name which you can use in CreateFile with the syntax \\.\MyLogicalDevicName (see http://msdn.microsoft.com/en-us/library/aa364014(VS.85).aspx).
If you want to send IOCTL codes with respect of DeviceIoControl function to a device, you should use 0 instead of GENERIC_READ | GENERIC_WRITE as the second parameter of CreateFile (see http://msdn.microsoft.com/en-us/library/aa363147(v=VS.85).aspx)
|
3,118,430 | 3,118,482 | Applying a function to 2 stl vectors | I'm currently trying to learn how to effectively use the STL part of c++. Say there are 2 vectors of the same type of equal length that need to be transformed into another vector of the same length by applying some operator, is there a good way to do this using the functionality of the STL?
Here's some pseudocode for what I'm trying to do:
vector<T> a;
vector<T> b;
vector<T> result;
for (int i = 0; i < a.size(); ++i){
result.at(i) = a.at(i) op b.at(i);
}
where "op" is some operator that is defined for type T.
| You may need to do some checking on sizes, but generally you can use std::transform.
E.g. (for + - <functional> contains class templates for function objects for this and other binary operators)
std::transform( a.begin(), a.end(), b.begin(), result.begin(), std::plus<T>() );
You need to ensure that b.size() >= a.size() and result.size() >= a.size(). If result starts out empty then you can use a back_insert_iterator to fill it without having to resize the container first.
|
3,118,543 | 3,118,581 | Need help deciphering gprof output | I am pretty sure this has something to do with a vector of void function pointers, but I can't really make anything out of it.
Can someone break this down for me?
__gnu_cxx::__normal_iterator<unsigned long long const*, std::vector<unsigned long long, std::allocator<unsigned long long> > >::difference_type __gnu_cxx::operator-<unsigned long long const*, unsigned long long const*, std::vector<unsigned long long, std::allocator<unsigned long long> ...> >(__gnu_cxx::__normal_iterator<unsigned long long const*, std::vector<unsigned long long, std::allocator<unsigned long long> > > const&, __gnu_cxx::__normal_iterator<unsigned long long const*, std::vector<unsigned long long, std::allocator<unsigned long long> > > const&)
| If I am correct, this could be roughly translated to:
// Typedef for brevity
typedef vector<unsigned long long>::iterator uv_iter;
// Actual function
uv_iter::difference_type operator-(const uv_iter &, const uv_iter &);
So, probably it is referring to the function that computes the difference (=distance) between two iterators of a vector. Anyhow, when the optimizer is on such function should actually be turned in a simple inlined pointers comparison.
|
3,118,552 | 3,118,922 | Using DLL import/Declare in VB.NET with parameter types not used by .NET | I am working on a project where I have to import a DLL file into a VB project that was created a few years back. The DLL was created in C++, and looks like:
void CoordinateConversionService::convert( SourceOrTarget::Enum sourceDirection, SourceOrTarget::Enum targetDirection, CoordinateTuple* sourceCoordinates, Accuracy* sourceAccuracy, CoordinateTuple& targetCoordinates, Accuracy& targetAccuracy )
I am an intern at my job, and I haven't had to use this yet, so my understanding is extremely limited, along with my usage of VB (I'm a C++/C# guy). Here are a few questions:
1) Looking at Dllimport, it seems like the last part outside of the parameters is a return type. Example code from another site:
<DllImport("advapi32.dll")> _
Public Function GetUserName( _
ByVal lpBuffer As StringBuilder, _
ByRef nSize As Integer) As Boolean
Is "As Boolean" the return type? If so, I tried using "Sub" and it says "Keyword does not name a type." Hence why I looked into declare, because it seems I CAN return void/sub as a return type.
2) Trying to use the types "CoordinateTuple" and "Accuracy" give me problems, saying that they aren't defined. How do I get around this since I don't think I can really define them, and what about the fact that they're pointers? Also - I cannot modify the C++ code in any way, so what I have is what I have.
| In VB you say either Public Function Whatever (params) As ReturnType (which is the same as public ReturnType Whatever(params) in C#) or Public Sub Whatever (params) which is for things that don't return anything (return void in C++/C#).
If your function/sub takes custom types you will need to declare .NET equivalents to those as well. This can make PInvoke hard work. Tools like the interop assistant can help.
|
3,118,582 | 3,118,775 | How do I find the current system timezone? | On Linux, I need to find the currently configured timezone as an Olson location. I want my (C or C++) code to be portable to as many Linux systems as possible.
For example. I live in London, so my current Olson location is "Europe/London". I'm not interested in timezone IDs like "BST", "EST" or whatever.
Debian and Ubuntu have a file /etc/timezone that contains this information, but I don't think I can rely on that file always being there, can I? Gnome has a function oobs_time_config_get_timezone() which also returns the right string, but I want my code to work on systems without Gnome.
So, what's the best general way to get the currently configured timezone as an Olson location, on Linux?
| It's hard to get a reliable answer. Relying on things like /etc/timezone may be the best bet.
(The variable tzname and the tm_zone member of struct tm, as suggested in other answers, typically contains an abbreviation such as GMT/BST etc, rather than the Olson time string as requested in the question).
On Debian-based systems (including Ubuntu), /etc/timezone is a file containing the right answer.
On some Redhat-based systems (including at least some versions of CentOS, RHEL, Fedora), you can get the required information using readlink() on /etc/localtime, which is a symlink to (for example) /usr/share/zoneinfo/Europe/London.
OpenBSD seems to use the same scheme as RedHat.
However, there are some issues with the above approaches. The /usr/share/zoneinfo directory also contains files such as GMT and GB, so it's possible the user may configure the symlink to point there.
Also there's nothing to stop the user copying the right timezone file there instead of creating a symlink.
One possibility to get round this (which seems to work on Debian, RedHat and OpenBSD) is to compare the contents of the /etc/localtime file to the files under /usr/share/zoneinfo, and see which ones match:
eta:~% md5sum /etc/localtime
410c65079e6d14f4eedf50c19bd073f8 /etc/localtime
eta:~% find /usr/share/zoneinfo -type f | xargs md5sum | grep 410c65079e6d14f4eedf50c19bd073f8
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/London
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Belfast
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Guernsey
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Jersey
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Isle_of_Man
...
...
Of course the disadvantage is that this will tell you all timezones that are identical to the current one. (That means identical in the full sense - not just "currently at the same time", but also "always change their clocks on the same day as far as the system knows".)
Your best bet may be to combine the above methods: use /etc/timezone if it exists; otherwise try parsing /etc/localtime as a symlink; if that fails, search for matching timezone definition files; if that fails - give up and go home ;-)
(And I have no idea whether any of the above applies on AIX...)
|
3,118,600 | 3,118,739 | Better compression algorithm for vector data? | I need to compress some spatially correlated data records. Currently I am getting 1.2x-1.5x compression with zlib, but I figure it should be possible to get more like 2x. The data records have various fields, but for example, zlib seems to have trouble compressing lists of points.
The points represent a road network. They are pairs of fixed-point 4-byte integers of the form XXXXYYYY. Typically, if a single data block has 100 points, there will be only be a few combinations of the top two bytes of X and Y (spatial correlation). But the bottom bytes are always changing and must look like random data to zlib.
Similarly, the records have 4-byte IDs which tend to have constant high bytes and variable low bytes.
Is there another algorithm that would be able to compress this kind of data better? I'm using C++.
Edit: Please no more suggestions to change the data itself. My question is about automatic compression algorithms. If somebody has a link to an overview of all popular compression algorithms I'll just accept that as answer.
| You'll likely get much better results if you try to compress the data yourself based on your knowledge of its structure.
General-purpose compression algorithms just treat your data as a bitstream. They look for commonly-used sequences of bits, and replace them with a shorter dictionary indices.
But the duplicate data doesn't go away. The duplicated sequence gets shorter, but it's still duplicated just as often as it was before.
As I understand it, you have a large number of data points of the form
XXxxYYyy, where the upper-case letters are very uniform. So factor them out.
Rewrite the list as something similar to this:
XXYY // a header describing the common first and third byte for all the subsequent entries
xxyy // the remaining bytes, which vary
xxyy
xxyy
xxyy
...
XXYY // next unique combination of 1st and 3rd byte)
xxyy
xxyy
...
Now, each combination of the rarely varying bytes is listed only once, rather than duplicated for every entry they occur in. That adds up to a significant space saving.
Basically, try to remove duplicate data yourself, before running it through zlib. You can do a better job of it because you have additional knowledge about the data.
Another approach might be, instead of storing these coordinates as absolute numbers, write them as deltas, relative deviations from some location chosen to be as close as possible to all the entries. Your deltas will be smaller numbers, which can be stored using fewer bits.
|
3,118,659 | 3,119,260 | How to avoid HDD thrashing | I am developing a large program which uses a lot of memory. The program is quite experimental and I add and remove big chunks of code all the time. Sometimes I will add a routine that is rather too memory hungry and the HDD drive will start thrashing and the program (and the whole system) will slow to a snails pace. It can easily take 5 mins to shut it down!
What I would like is a mechanism for avoiding this scenario. Either a run time procedure or even something to be done before running the program, which can say something like "If you run this program there is a risk of HDD thrashing - aborting now to avoid slowing to a snails pace".
Any ideas?
EDIT: Forgot to mention, my program uses multiple threads.
| You could consider using SetProcessWorkingSetSize . This would be useful in debugging, because your app will crash with a fatal exception when it runs out of memory instead of dragging your machine into a thrashing situation.
http://msdn.microsoft.com/en-us/library/ms686234%28VS.85%29.aspx
Similar SO question
Set Windows process (or user) memory limit
|
3,118,661 | 3,152,442 | Preventing SQL injection in C++ OTL, DTL, or SOCI libraries | I've been looking at all three of these database libraries, and I'm wondering if they do anything to prevent SQL injection. I'm most likely going to be building a lib on top of one of them, and injection is a top concern I have in picking one. Anybody know?
| Got with the author of the OTL library. A parameterized query written in "OTL Dialect," as I'm calling it, will be passed to the underlying DB APIs as a parameterized query. So parameterized queries would be as injection safe as the underlying APIs make them.
Go to this other SO post for his full e-mail explanation:
Is C++ OTL SQL database library using parameterized queries under the hood, or string concat?
Edit: SOCI uses the soci::use expression, which translates to the usual binding mechanism, but with more syntactic sugar. Example: db_session << "insert into table(column) values(:value_placeholder)", use(user_input,"value_placeholder");
As far as DTL is concerned, I'm not sure what it do with parameters in relation to the underlying APIs.
|
3,118,741 | 3,121,382 | memory leak: unable to break on a memory allocation number | I'm trying to locate a memory leak issue.
My project is an ATL based dialog project, that uses DirectShow and the standard library.
I get a total of 45 memory leaks in my program, all 24 bytes each.
I've #define'd _CRTDBG_MAP_ALLOC etc in my stdafx.h, along with DEBUG_NEW to get the file and line numbers for each of the memory leaks.
However, no file line numbers are printed. The memory blocks are all "normal" blocks and look like this:
{180} normal block at 0x003E6008, 24 bytes long. Data: < > _> > W > A0 AE 3E 00 B0 5F 3E 00 A0 AE 3E 00 57 00 00 00
I've tried adding the following line to the start of _tWinMain()
_CrtSetBreakAlloc(180);
in order to break on the allocation, but the debugger doesn't break at all.
Can anyone give me any insight into how I might track down the elusive memory leaks?
Finally, here's my _tWinMain() - I call _CrtDumpMemoryLeaks() just before exiting.
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow){
_CrtSetBreakAlloc(180);
HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
ATLASSERT(SUCCEEDED(hRes));
::DefWindowProc(NULL, 0, 0, 0L);
AtlInitCommonControls(ICC_BAR_CLASSES);
//HINSTANCE hInstRich = ::LoadLibrary(CRichEditCtrl::GetLibraryName());
hRes = _Module.Init(NULL, hInstance);
ATLASSERT(SUCCEEDED(hRes));
int nRet = Run(lpstrCmdLine, nCmdShow);
_Module.Term();
::CoUninitialize();
_CrtDumpMemoryLeaks();
return nRet;
}
| Two suggestions.
Firstly, what gets constructed before main (or equivalent) starts gets destroyed after main finishes. Calling _CrtDumpMemoryLeaks at the end of main can give you false positives. (Or are they false negatives?) Global objects' destructors have yet to run, and atexit callbacks have yet to run, so the leak output will include allocations that have simply yet to be correctly freed.
(I suspect this is why your global objects are appearing to leak. There may well be nothing wrong with the code, and indeed it's quite possibly cleaning itself up properly -- the cleanup code has simply yet to run when _CrtDumpMemoryLeaks is being called.)
What you need to do instead is to direct the runtime library to call _CrtDumpMemoryLeaks for you, right at the end, after all the atexit callbacks and global object destructors have finished. Then you'll only see the genuine leaks. This snippet will do the trick. Stick at at the start of main:
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)|_CRTDBG_LEAK_CHECK_DF);
Secondly, if the above reveals genuine leaks from stuff that runs before main, you can do a bit of trickery to get some of your own code running pretty much before anything else gets a look in. Then you can set _crtBreakAlloc before any allocations happen. Just pop the following code in a .cpp file of its own:
#include <crtdbg.h>
#ifdef _DEBUG
#pragma warning(disable:4074)//initializers put in compiler reserved initialization area
#pragma init_seg(compiler)//global objects in this file get constructed very early on
struct CrtBreakAllocSetter {
CrtBreakAllocSetter() {
_crtBreakAlloc=<allocation number of interest>;
}
};
CrtBreakAllocSetter g_crtBreakAllocSetter;
#endif//_DEBUG
(I suspect that code in the compiler's init segment may well run before stdin and stdout and the like are initialised, and certainly before any global objects are constructed, so you may have difficulty doing anything more complicated than the above!)
(For what little it's worth, I'm of the opinion these days, and have been for some time now, that allocation before main starts is almost always a bad thing. Makes it hard to clean up after oneself, and difficult to keep track of what's going on. It's certainly convenient, but you always seem to end up paying for it later. That's advice that's much easier to hand out than it is to implement, though, particularly as part of a larger team.)
|
3,118,920 | 3,119,182 | Building a project with CMake including other libraries which uses different build systems | I am working on an open source project which uses C for libraries, C++ for GUI and Cmake for managing build. This project is just started and have only couple of files. I can successfully generate makefiles on my linux development environment and on windows I can generate Visual Studio project files using CMake. All works well so far.
As the project is evolving, I am in a stage where I need a testing framework. I have good experience with UnitTest++ which will work well on all popular platforms.
The problem is, I have no clue to integrate the UnitTest++ build with CMake (they use makefile on linux and visual studio project files are available for windows). I need to build UnitTest++ files to generate a library before my code is built. How can I specify this in CMake in a way which will work on linux and windows?
| I'm using this CMakeLists.txt:
#/**********************************************************\
#Original Author: Richard Bateman (taxilian)
#
#Created: Nov 20, 2009
#License: Dual license model; choose one of two:
# New BSD License
# http://www.opensource.org/licenses/bsd-license.php
# - or -
# GNU Lesser General Public License, version 2.1
# http://www.gnu.org/licenses/lgpl-2.1.html
#
#Copyright 2009 PacketPass, Inc and the Firebreath development team
#\**********************************************************/
cmake_minimum_required (VERSION 2.8)
project (UnitTest++)
message ("Generating project ${PROJECT_NAME}")
include_directories (
${CMAKE_CURRENT_SOURCE_DIR}/src
)
list (APPEND SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/AssertException.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/Test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/Checks.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TestRunner.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TestResults.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TestReporter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TestReporterStdout.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/ReportAssert.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TestList.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TimeConstraint.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/TestDetails.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/MemoryOutStream.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/DeferredTestReporter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/DeferredTestResult.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/XmlTestReporter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/CurrentTest.cpp
)
if (UNIX)
list(APPEND SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/Posix/SignalTranslator.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/Posix/TimeHelpers.cpp
)
elseif (WIN32)
list(APPEND SOURCES
src/Win32/TimeHelpers.cpp
)
endif()
add_library (UnitTest++ STATIC ${SOURCES})
add_definitions(
-D_CRT_SECURE_NO_DEPRECATE
)
if (UNIX)
set_target_properties(UnitTest++ PROPERTIES
COMPILE_FLAGS "-g -Wall -W -ansi"
)
endif(UNIX)
|
3,118,927 | 3,120,026 | C++ Integer overflow problem when casting from double to unsigned int | I need to convert time from one format to another in C++ and it must be cross-platform compatible. I have created a structure as my time container. The structure fields must also be unsigned int as specified by legacy code.
struct time{
unsigned int timeInteger;
unsigned int timeFraction;
} time1, time2;
Mathematically the conversion is as follows:
time2.timeInteger = time1.timeInteger + 2208988800
time2.timeFraction = (time1.timeFraction * 20e-6) * 2e32
Here is my original code in C++ however when I attempt to write to a binary file, the converted time does not match with the truth data. I think this problem is due to a type casting mistake? This code will compile in VS2008 and will execute.
void convertTime(){
time2.timeInteger = unsigned int(time1.timeInteger + 2209032000);
time2.timeFraction = unsigned int(double(time1.timeFraction) * double(20e-6)*double(pow(double(2),32)));
}
| Just a guess, but are you assuming that 2e32 == 2^32? This assumption would make sense if you're trying to scale the result into a 32 bit integer. In fact 2e32 == 2 * 10^32
|
3,119,206 | 3,168,539 | Weird unresolved external errors in linked objects | Using Visual Studio 10 C++, I'm having weird link error. For some reason references to a global object won't link to that global object. It is telling me a symbol is undefined yet when I have it view the .cod file the symbol is right there plain as day.
The error:
FTShell.lib(ftcommodule.obj) : error LNK2001: unresolved external symbol
"class CFTModuleShellBase * _pFTModule" (?_pFTModule@@3PAVCFTModuleShellBase@@A)
But the .cod file for the main cpp file shows both the declaration and allocation of the global symbol:
PUBLIC ?_pFTModule@@3PAVCFTModuleShellBase@@A ; _pFTModule
_DATA SEGMENT
?_pFTModule@@3PAVCFTModuleShellBase@@A DD FLAT:?_Module@@3VCFTComModule@@A ; _pFTModule
ORG $+4
So why wouldn't the static library's _pFTModule be matching the global symbol in my source file?
EDIT: I ran msbuild from the command line:
Link:
C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\link.exe
/ERRORREPORT:QUEUE.... "C:\(path)\FTTrace.res"
"C:\(path)\FTTrace.obj"
And I noticed at the end there is only one .obj file. There are two .cpp files in the project. And MSBUILD did build both file. So why didn't it pass both files on to the linker. The .vcxproj file doesn't treat the .cpp files differently. Why would MSBUILD not include both files on the link step?
<ItemGroup>
<ClCompile Include="FTTrace.cpp" />
<ClCompile Include="TraceImpl.cpp" />
</ItemGroup>
| Strangely enough, the error was the result of setting the ImpLib property to a bad value. The property sheet said: <ImpLib>$(OneOfMyPathVars)\%(Filename).lib</Implib>. Since %(Filename) was empty during the link stage "C:\foo.lib" causes no ImpLib to be created. And that caused the unresolved externals from functions declared in the project. Probably a bug in the linker but it was self-inflicted.
|
3,119,222 | 3,119,262 | casting LPCWSTR to LPCSTR | got this code from a website that helped me in creating buttons and stuff. the buttons work but for some reason im getting an compiler error with the creating a static.
cannot convert from 'const wchar_t [5]' to 'char'
cannot convert parameter 3 from 'char' to 'LPCWSTR'
is there a simply way to fix this? i tried casting lyrics into another variable and making it just a char.
static char *lyrics = TEXT("Dood");
switch (message)
{
case WM_CREATE:
{
CreateWindow(TEXT("button"), TEXT("Beep"),
WS_VISIBLE | WS_CHILD ,
20, 300, 80, 25,
hWnd, (HMENU) 1, NULL, NULL);
CreateWindow(TEXT("button"), TEXT("Quit"),
WS_VISIBLE | WS_CHILD ,
120, 300, 80, 25,
hWnd, (HMENU) 2, NULL, NULL);
CreateWindow(TEXT("STATIC"), lyrics,
WS_CHILD | WS_VISIBLE | SS_LEFT,
20, 20, 300, 230,
hWnd, (HMENU) 1, NULL, NULL);
| Try this instead:
static TCHAR *lyrics = TEXT("Dood");
With the compiler settings you appear to have, TCHAR will be converted to wchar_t.
|
3,119,238 | 3,119,261 | Whats wrong with this c++ reverse string function | void reverse (char s[]){
int len = strlen(s);
int j = len - 1;
for (int i = 0; i < j; i++,j--){
cout << s[i];
char ch = s[i];
s[i] = s[j]; //error line - giving exception, cannot write to the memory
s[j] = ch;
}
}
I am using Visual Studion 2008 and i can't understand whats the problem here .. :s .. I am out of C++ practice :$ .
| The problem is that it uses C-style strings instead of C++ style strings. In particular, you are apparently trying to write to a constant string literal:
char const* str = "I cannot be written to";
C++ allows to omit the const here for backwards compatibility but the literal is still constant.
Finally, C++ already has a reverse function:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
|
3,119,275 | 3,127,790 | Custom draw CTreeCtrl: how to add font strike through? | I have implemented custom draw for an CTreeCtrl in my MFC Smart Device program. I have successfully changed the color of specific nodes of the CTreeCtrl. I am now trying to understand how to get the default font used to draw text in the control so I can add a strike-through to the font for certain nodes. How would I go about getting the default font used to draw text in the CTreeCtrl and apply a font strike-through to the font?
| Use GetFont() to get the font of the control. Strike-through can't be done with ::DrawText AFAIK, but it's easy to just add a GoTo()/LineTo(). You can use GetTextExtent() to get the size of the bounding rectangle and derive the left/right of the strike through line from that.
|
3,119,405 | 3,119,451 | Variable and loops convertion from VB.NET to C++? | Is there any available tool for converting variable and loops declarations from VB.NET to C++?
| If you're talking about C++/CLI then you may consider using Reflector.NET to convert VB.NET to C++/CLI. If you're talking about managed/unmanaged bridge then .net framework does that for you (marshalling).
|
3,119,431 | 3,119,512 | c++ rvalue passed to a const reference | I'm trying to understand exact C++ (pre C++0x) behavior with regards to references and rvalues. Is the following valid?
void someFunc ( const MyType & val ) {
//do a lot of stuff
doSthWithValue ( val);
}
MyType creatorFunc ( ) {
return MyType ( "some initialization value" );
}
int main () {
someFunc ( creatorFunc() );
return 0;
}
I found similar code in a library I'm trying to modify. I found out the code crashes under Visual Studio 2005.
The way I understand the above, what is happening is:
creatorFunc is returning by value, so a temporary MyType object obj1 is created. (and kept... on the stack?)
someFunc is taking a reference to that temporary object, and as computation progresses the temporary object is overwritten/freed.
Now, what is mind-boggling is that the code most often works fine. What is more, with a simple piece of code I cannot reproduce the crash.
What is happening/supposed to happen here? Does is matter if the reference (val) is const or not? What is the lifespan of the object returned from creatorFunc?
| The return value has the lifetime of a temporary. In C++ that means the complete expression that created the type, so the destructor of MyType shouldn't be called until after the call to someFunc returns.
I'm curious at your 'is overwritten/freed'. Certainly calling delete on this object is not OK; it lives on the stack and deleting it would probably cause heap corruption. Also, overwriting/modifying it could also be bad. Your example uses a constant "C string"; on many compilers values like this are stored in read-only memory, so attempting to modify it later could cause a crash/access violation. (I'm not sure if Visual C++ does this optimization, however).
There is a big difference between passing a temporary by const versus mutable references. Creating a mutable reference to a temporary is not allowed by standard C++, and most compilers (including GCC) will reject it, though at least some versions of Visual C++ do allow it.
If you are passing it with a mutable reference, what you want to write is:
MyType t = creatorFunc();
someFunc(t);
|
3,119,441 | 3,119,458 | How can i make a text box that changes input constantly? | So I want to create a text box "static if possible" that when my user interacts with the story game the text inside changes to accommodate his action. so im guessing i want a pointer to the char variable, but it seems that i cant figure out how to do this... can someone help me please.
im thinking create the static box with a argument that is a pointer, so i can constantly change its address to another string of text. would this work? because at the moment im changing the value of the char string and nothing is happening.
| To change the content of a standard Win32 textbox, you simply send the WM_SETTEXT message.
|
3,119,578 | 3,149,503 | AIX 6.1 linker error | I'm trying to compile my application on AIX. It builds fine on Linux, Solaris x86 and Windows but this is the first time we've tried to build on AIX.
I've managed to get to the point of linking all of the libraries together and I get the error message:
Linking...
ld: 0711-101 FATAL ERROR: Allocation of 96864 bytes failed
in routine get_RLDs. There is not enough memory available.
Please check your ulimit or paging space
or use local problem reporting procedures.
collect2: ld returned 12 exit status
I've increased the page space by 1GB - no difference
I've increased the ulimit values - no difference
I've tried passing in the maxdata flag to the linker - no difference
Is there anything else I should be trying?
I'm not sure how to identify which library is causing the problem. We're trying to link statically against boost_date_time, xerces-c and libz and against 50 internal libraries. I can't change to dynamic linking and I can't change much about the structure of the system so I'm looking for ideas of configuration or parameters to try for ld.
| The problem turned out to be the ulimit on the data seg size. Apparently that was still set quite small. Making it bigger like:
ulimit -d 1048575
allows the linker to get further.
Now to just figure out what I do about all of these undefined symbols.
|
3,119,650 | 3,119,742 | How to set a zmq socket timeout | I've got client and server applications using zmq in the ZMQ_REQ context. What I'm experiencing is that when the server component goes down or is unavailable, the client will wait until it is available to send its message. Is there a way to set a max wait time or timeout at the client level?
| I would guess you can use the zmq_poll(3) with a timeout greater then zero.
|
3,119,694 | 3,120,784 | Compare matrices multiplication | I must multiply a matrix by itself until the matrix in some degree would not be equal to one of the preceding matrices. Then I need to get the values of degrees in which the matrices are equal. The number of rows and columns are equal. The matrix is stored in a two-dimensional array. Values are 0 or 1. What is the best way to check for equality with the previous matrices? I tried to use vector to store matrices:
vector<int[5][5]> m;
but I got an error cannot convert from 'const int [5][5]' to 'int [5][5]'.
Waiting for an advice.
| If you can use boost, look at the boost Matrix class:
It seems to be missing an == operator, but it's easy to add:
#include <iostream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
template<typename T>
bool operator==(const matrix<T>& m, const matrix<T>& n)
{
bool returnValue =
(m.size1() == n.size1()) &&
(m.size2() == n.size2());
if (returnValue)
{
for (unsigned int i = 0; returnValue && i < m.size1(); ++i)
{
for (unsigned int j = 0; returnValue && j < m.size2(); ++j)
{
returnValue &= m(i,j) == n(i,j);
}
}
}
return returnValue;
}
And used like so:
int main ()
{
matrix<double> m (3, 3);
for (unsigned int i = 0; i < m.size1(); ++ i)
{
for (unsigned int j = 0; j < m.size2(); ++ j)
{
m (i, j) = 3 * i + j;
}
}
std::cout << m << std::endl;
matrix<double> n (3, 3);
std::cout << (m == n) << std::endl;
std::cout << (m == m) << std::endl;
}
[Code]
|
3,119,714 | 3,119,774 | Skipping Incompatible Libraries at compile | When I try to compile a copy of my project on my local machine, I get an error stating that it 's skipping over incompatible libraries. This isn't the case when I'm messing around with the live version hosted on the server at work [it makes perfectly there].
Various other sites have lead me to believe that this might be an environment issue, as I'm developing on a 64-bit distro of Ubuntu and I assume the server version is running on 32-bit. Nevertheless, after setting my environment variables to:
CFLAGS+=" -m32"
CXXFLAGS+=" -m32"
I still receive the same compile error of:
/usr/bin/ld: skipping incompatible /dvlpmnt/libPI-Http.a when searching for -lPI-Http
Can haz tutorial?
==Edit==
This was the output I recieved when I followed Jonathan's advice:
http.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
Apparently, the library in question is 32-bit after all?
| That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.
Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)
It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:
Just to check: usually you would add
flags to CFLAGS rather than
CTAGS - are you sure this is
correct? (What you have may be correct - this will depend on your build system!)
Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS
If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?
|
3,119,842 | 3,119,978 | Having difficulty in storing a QImage and then recovering it | Ok well I'm trying implement something similar to the 'undo' function in many image drawing programs .. The problem I'm having is this: I'm trying to make a backup copy of a QImage object in a QVector (which stores upto 10 latest QImage copies for backup purposes), and then try to retrieve these backups in another function. The issue is that the backup is not being created properly (since when I try to recover a backuped image, nothing happens). I know the problem is somewhere in backing up part and not in the recovering part, since when I backup a new temporary image with a red background, it recovers perfectly ..
This is the backing up function code:
imageBackups.append(image);
where 'image' is the QImage object that I'm trying to backup ..
This is an alternate backing up (stores a red colored background image) - I used this just to see if this version of backing up works, which it does:
QImage newImage(QSize(100,100), QImage::Format_RGB32);
newImage.fill(qRgb(255, 0, 0));
imageBackups.append(newImage);
And here is the recovering code:
image =imageBackups.at(imageBackups.size()-1);
QPainter painter(&image);
painter.drawImage(QPoint(0,0),imageBackups.at(imageBackups.size()-1));
'image' is defined exactly like newImage above, except the size which is 800x400 in this case..
| It may has something to do with how you created image. If you use one of the constructors that takes a uchar * buffer (const or not), you have to make sure the buffer is valid through out the life of the QImage and its copies:
http://doc.trolltech.com/latest/qimage.html#QImage-5
If at the time of your restoring of the image from QVector, the buffer is deleted, the restored QImage will be using some stale memory location as it's buffer.
|
3,119,923 | 3,120,332 | Creating an OS close button? (WinAPI) | I want to create a button that is basically Windows' close button. How could I do this? I want to avoid drawing this myself because I want it to look like that version of Windows' close button. Firefox's tabs do something like this. Thanks
| You can get at Windows XP+ theme specific UI elements via the DrawThemeBackground API.
Use WP_CLOSEBUTTON for the window X button (and one of CBS_NORMAL/HOT/PUSHED/DISABLED for its state) and you can draw one wherever you like.
|
3,119,929 | 3,120,537 | Forwarding all constructors in C++0x | What is the correct way to forward all of the parent's constructors in C++0x?
I have been doing this:
class X: public Super {
template<typename... Args>
X(Args&&... args): Super(args...) {}
};
| There is a better way in C++0x for this
class X: public Super {
using Super::Super;
};
If you declare a perfect-forwarding template, your type will behave badly in overload resolution. Imagine your base class is convertible from int and there exist two functions to print out classes
class Base {
public:
Base(int n);
};
class Specific: public Base {
public:
template<typename... Args>
Specific(Args&&... args);
};
void printOut(Specific const& b);
void printOut(std::string const& s);
You call it with
printOut("hello");
What will be called? It's ambiguous, because Specific can convert any argument, including character arrays. It does so without regard of existing base class constructors. Inheriting constructors with using declarations only declare the constructors that are needed to make this work.
|
3,120,340 | 3,121,012 | Visual Studio Addin "Exclude From Build" Property | I am currently trying to create an addin for Visual Studio 2008 that will list all files which are not excluded from the current build configuration.
I currently have test C++ console application that has 10 files, 2 of which are "Excluded From Build". This is a property that will allow a specific file to be excluded from a specific configuration (i.e. Debug or Release). This property is located when you right click on a file in the solution explorer and select Properties->Configuration Properties->General->Excluded From Build
At the moment I have the following code that will loop though all project files and get the properties for each file.
foreach (Project theProject in _applicationObject.Solution.Projects)
{
getFiles(theProject.ProjectItems);
}
private void getFiles(ProjectItems theItems)
{
foreach (ProjectItem theItem in theItems)
{
string theItemName = theItem.Name;
foreach (Property theProp in theItem.Properties)
{
string thePropName = theProp.Name;
}
getFiles(theItem.ProjectItems);
}
}
The issue I am having is that I cant seem to find the "Excluded From Build" property. I cannot find very good documentation on what properties are listed where. Where is this Excluded From Build property located within the _applicationObject object?
| I'm not familiar with the Visual Studio object model, but in the documentation for VS2005 the following objects have an ExcludedFromBuild property:
VCFileConfiguration
VCFileConfigurationProperties
VCPreBuildEventTool
VCPreLinkEventTool
VCPostBuildEventTool
VCWebDeploymentTool
Hopefully this will lead you down the right path.
|
3,120,461 | 3,120,573 | Should I learn Java or should I learn C++? | I have a pretty good non-OOP background. I've done lots of Visual Basic coding, and a little SQL.
I want to widen my skillset and be more marketable. Most of my experience has been working with scientific companies, and I've been supporting scientists a lot.
I want to take some online classes from my local community college. Should I take Java or C++ programming? My goal is to be more marketable. Some more background information: I've had a little bit of experience with .NET, and I am assuming that since I know C# a bit, it may be worthwhile for me to get into C++?
Should I learn Java or C++?
I beg you please don't close this question. Give me 10 minutes to see everyone's input.
| I am a recent Computer Science graduate and from my job search I have to say that there are many more people wanting Java programmers than C++. I also saw a great deal of people looking for C# programmers. C++ is not being used as much outside of the academic and scientific field right now.
Java and C# are also similar languages so once you understand one you should be able to go to the other.
If you do want to do C++ that is fine. If you can learn C++ and then master C then you will be in a good position for those few places that need incredibly skilled C programmers. C++ and C are able to reach to a lower level (closer to the hardware) more easily than Java and C# can. That is why they are used mostly in the areas that are dealing with specific and custom hardware.
|
3,120,483 | 3,120,999 | strange garbage data when opening a previously truncated file | In my program, I've redirected stdout to print to a file 'console.txt'. A function writes to that file like this:
void printToConsole(const std::string& text, const TCODColor& fc, const TCODColor& bc)
{
// write the string
cout << text << "@";
// write the two color values
cout << static_cast<int>(fc.r) << " "
<< static_cast<int>(fc.g) << " "
<< static_cast<int>(fc.b) << " "
<< static_cast<int>(bc.r) << " "
<< static_cast<int>(bc.g) << " "
<< static_cast<int>(bc.b) << " " << endl;
}
I have a function that reads from that file that looks like this:
void Console::readLogFile()
{
ifstream log("console.txt", ifstream::in);
if(!log.is_open())
{
cerr << "ERROR: console.txt not found!" << endl;
return;
}
// read new input into Console
string str;
while(getline(log, str))
{
cerr << "str: " << str << endl;
/* do stuff with str here */
}
cerr << endl;
log.close();
clearLogFile();
}
void Console::clearLogFile()
{
ofstream("console.txt", ios_base::trunc);
}
The first time through the readLogFile, everything works fine. Afterwards, however, it starts to have problems. It will read in the first line of console.txt as a blank string. I stepped through the program with console.txt open in gvim, and monitored how it changed. The first time through, when it worked correctly, console.txt looks something like this:
1 moved UP.@191 191 191 0 0 0
2 Player moved.@191 191 191 0 0 0
~
~
which is as it should be. The program then goes to clearLogFile, and afterwards console.txt is empty. However, the second time through, when I open the ifstream, console.txt looks like this:
1 ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@moved UP.@191 191 191 0 0 0
2 Player moved.@191 191 191 0 0 0
~
~
This time, when getline reads the first line into str, str is blank. Strangely, the cerr << "str: " << str << endl; line still prints str as "moved UP.@191 191 191 0 0 0", even though inspecting str in gdb reveals that it's empty.
Anyone know what's going on here?
| The routine that is writing is not resetting it's file position before rewriting to the file. As a result it starts off at an offset into the target file.
I believe a cout.seekp(0) after performing the write will reset the write pointer, thus restarting the write at the start of the file.
You're probably going to have a lot of problems with consistency of the content of the logfile with the way you're using it, though.
Comment added here, as I can't get formatting in the comment box...
By resetting the file pointer after every write, there will only ever be one line in the output file. You need to make sure that you read it before you write to it, otherwise the new data will be over-written by the old data, or worse may be partially overwritten.
e.g. write 1:
Player moved 1 2 3 4
e.g. write 2:
Player fell over
Would leave:
Player fell over
3 4
In the written file if the reader didn't get there before the writer made it's second write.
You may be better off using an explicit file, rather than using cout, or you could remember the read position between reads and seek to that before performing your next read, but that leaves you with an ever growing logfile.
HTH
|
3,120,571 | 3,120,608 | eclipse C++ add reference undefined reference to method error | I'm new to C++ and ecplice and they are definitely giving my a hard time :)
I'm tring to write simple application that includes main project with refernces to other project
i wrote the following file in shared project:
#ifndef MANAGEDLOG_H_
#define MANAGEDLOG_H_
#include string
#include iostream
#include fstream
using namespace std;
class ManagedLog
{
ofstream _fileStream;
public :
ManagedLog::ManagedLog(string path);
ManagedLog::~ManagedLog();
void ManagedLog::WriteInfoLog(string message,string stackTrace);
};
#endif /* MANAGEDLOG_H_ */
/*
* ManagedLog.cpp
*
* Created on: 18/06/2010
* Author: Eran
*/
#include "ManagedLog.h"
#include iostream
#include fstream
ManagedLog::ManagedLog(string path)
{
_path=path;
}
ManagedLog::~ManagedLog()
{
}
void ManagedLog:: WriteInfoLog(string message,string stackTrace)
{
ofstream myfile;
myfile.open("Eample.txt",ios::app);
myfile.close();
}
and run it in simple hellow world project:
#include "ManagedLog.h"
#include
using namespace std;
int main() {
ManagedLog * log = new ManagedLog("path");
log->WriteInfoLog("test","RunLog/Main");
cout
but I'm getting this error:
*** Build of configuration Debug for project RunLog ****
**** Internal Builder is used for build ****
g++ -ID:\EclipseWorkSpace\LogManager -O0 -g3 -Wall -c -fmessage-length=0 -osrc\RunLog.o ..\src\RunLog.cpp
g++ -LD:\EclipseWorkSpace\LogManager\Release -oRunLog.exe src\RunLog.o
src\RunLog.o: In function `main':
D:/EclipseWorkSpace/RunLog/Debug/../src/RunLog.cpp:13: undefined reference to `ManagedLog::ManagedLog(std::string)'
D:/EclipseWorkSpace/RunLog/Debug/../src/RunLog.cpp:14: undefined reference to `ManagedLog::WriteInfoLog(std::string, std::string)'
collect2: ld returned 1 exit status
Build error occurred, build is stopped
Time consumed: 574 ms.
I added #include "ManagedLog.cpp" and the code work just fine but i guess this is not the right way to do it i read a lot about it but found no answer that i can impliment since i don't understad the term is the reanswers can anybody please help me with the right way to point to other project or dll in this environment?
thanks
Eran
| You're not building ManagedLog.cpp. Your compile sequence should look something like this example (simplified for clarity):
compile RunLog.c into RunLog.o
compile ManagedLog.c into ManagedLog.o
link RunLog.o and ManagedLog.o into RunLog.exe
Steps 1 & 2 could be in the other order if you like.
|
3,120,951 | 3,120,974 | g++ template problem | I'm porting my c++ windows code (msvc & intel) to Linux (g++). The code uses lots of templates (I like metaprogramming ;-). But I can't compile this code:
template <class TA>
struct A
{
template <class TAB> struct B;
};
template <class TC>
struct C {};
template <class TD>
struct D
{
template <class TTD> class T {};
};
template<class TA>
template<class TBA>
struct A<TA>::B : C<typename D<TA>::T<TBA> >
{
int foo;
};
g++ tells me that in definition of A::B, C class has invalid template arguments. But on msvc and intel it works well! What's the problem here?
PS: Sorry, I can't post the original code, because it's too template-complicated. But this example is virtually the same and gives the same error on g++.
Thank you.
UPDATE: I've found the problem is in TBA argument of T. g++ doensn't like usage of second template in the definition.
| You need the template keyword
template<class TA>
template<class TBA>
struct A<TA>::B : C<typename D<TA>::template T<TBA> >
{
int foo;
};
GCC is correct to give a diagnostic here. This is because T cannot be looked up in the dependent scope D<TA>. The meaning of the < after it depends on whether T is a template or not. The Standard says that T shall be assumed to be not a template and thus T cannot be followed by a template argument list.
template is like typename in that it tells the compiler to treat T as a template and that the < is the start of an argument list in any case. The Standard says in paragraphs 14.2/2 and 14.2/4
For a template-name to be explicitly qualified by the template arguments, the name must be known to refer
to a template.
When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.
In your case, you have T appear after the nested-name-specifier D<TA> which depends on the template-parameter TA. For the typename-specifier to parse correctly, the construct D<TA>::T<TBA> must interpret T as the name of a class template, which 14.2 forbids.
On that topic, it's always a good idea to try and compile with Clang
main1.cpp:21:37: error: use 'template' keyword to treat 'T' as a dependent template name
struct A<TA>::B : C<typename D<TA>::T<TBA> >
^
template
1 error generated.
|
3,121,308 | 3,121,395 | Ensuring fields are only added to the end of a struct? | I have a rather odd problem: I need to maintain a chunk of code which involves structs. These structs need to be modified by adding fields to them from time to time. Adding to the end of a struct is what you are supposed to do, and any time you add a field to the middle of a struct, you've broken the code in a non-trivial way.
It's become a nightmare to maintain since these do need to be modified occasionally, and the only way to get out of the business of modifying these structs (and having them break due to the layout change of the previous fields) is to completely rewrite a huge swath of code, which is simply not possible.
What I need to do is find a way to make changing the layout of the struct a compile error. Now, I can solve the problem this way:
struct Foo
{
int *Bar;
int Baz;
};
#ifdef _x86_
static_assert(_offsetof(Foo, Bar) == 0);
static_assert(_offsetof(Foo, Baz) == 4);
#else
static_assert(_offsetof(Foo, Bar) == 0);
static_assert(_offsetof(Foo, Baz) == 8);
#endif
However, this is a huge amount of work because there are roughly 20 of these structs with 4-10 fields each. I can probably minimize this by only asserting that the last field's offset is at the correct location, but this is still a lot of manual work.
Does anyone have any suggestions for a compiler trick, C++ template metaprogram trick, or otherwise, that would make this easier?
| you should probably use a form of struct inheritence (c -style) to make this a little easier for everyone to figure out
basically you would have the struct you dont want modified
//DO not modify this structure!!!
struct Foo
{
int *Bar;
int Baz;
};
and a FooExtensions (or whatever) struct that people can modify willy-nilly
struct FooExtensions
{
struct Foo base;
//go crazy but keep base as the first thing.
};
then to pass a FooExtnesions object to a method expecting a Foo just cast it to Foo, the member alignments will work out. this is a more common pattern for maintaining this kind of backwards compatibility. Obviously people can still ignore the convention but this makes it a little easier to succeed.
you can still add all the static_asserts to make sure that Foo isn't modified
|
3,121,344 | 3,121,376 | Why is only one implicit conversion allowed to resolve the parameters to a function in C++? | This works:
#include<cstdio>
class A{
public:
A(int a):var(a){}
int var;
};
int f(A obj) {
return obj.var;
}
int main() {
std::cout<<f(23); // output: 23
return 0;
}
while this doesn't:
#include<cstdio>
class A{
public:
A(int a, int b):var1(a), var2(b){}
int var1, var2;
};
int f(A obj) {
return (obj.var1 + obj.var2);
}
int main() {
cout<<f(22, 23); // error: conversion from 'int' to
// non-scalar type 'A' requested
return 0;
}
The second piece of code does not work, but I am not able to find a good-enough reason why it doesn't. To me, the code just looks too odd to work.
But what is the actual reason that there is only one implicit conversion allowed in situations like this? Is it a this-is-like-this-only language feature?
| The direct answer is that the C++ grammar does not combine function arguments into aggregates under any circumstances. In no case will a call to f(a, b) be treated as a call to f(c) where c is a value constructed from some combination of a and b. That's just not how the language works. Each argument is always treated separately for overloading, implicit conversion, and all other purposes.
As for a rationale, if what you're asking about were allowed, how would you expect this situation to be resolved:
class A {
public:
A(int a) : v1(a) {}
private:
int v1;
};
class B {
public:
B(int a, int b) : v1(a), v2(b) {}
private:
int v1;
int v2;
};
class C {
public:
C(int a, int b, int c) : v1(a), v2(b), v3(c) {}
private:
int v1;
int v2;
int v3;
};
void f(A obj1, A obj2) { /* ... */ }
void f(B obj) { /* ... */ }
void g(A obj1, B obj2) { /* ... */ }
void g(B obj1, int i) { /* ... */ }
void g(C obj) { /* ... */ }
int main() {
f(22, 23); // Call f(A,A) or f(B)?
g(22, 23, 24); // Call g(A,B) or g(B, int), or g(C)?
return 0;
}
|
3,121,362 | 3,121,537 | How to write modern Windows software in C++? | I am very interested in how modern Windows software is written in C++ nowadays. I asked my friend who had worked on Windows software and he told that last things he worked with were MFC and then WTL. He said that MFC is no longer anything modern but WTL is still used but he didn't know much more. He also said that WTL wasn't that modern and before that he programmed in pure Windows API.
How does one write software for Windows Vista or Windows 7? Do you still use WTL? What about MFC and pure Windows API? Or are there other libraries now?
I don't know much about it, but have C# or other .NET languages replaced C++ in writing modern Windows software?
| From what I've seen over the past several years:
WTL is on a lifeline. Abandoned by Microsoft, picked up by fans and there were several very dedicated followers. Very clean, but the learning curve is steep and the fan base dwindling. The Yahoo group is not very active. I can't recommend it.
MFC got another lease on life when MSFT released the feature pack. Rather extensive and a bit un-MFC-ish, it has strong support for skinning, docking layouts and ribbons. I thought it was going to be wildly popular but never did see a lot of devs jumping on it. MSDN forum questions have been sparse. If you have an existing MFC codebase then definitely take a look. Another MFC refresh for VS2010 with Win7 features added, it does stay the company's base UI solution.
wxWidgets is still around. No personal experience, but Lord, the few practitioners I've heard from are bitching up a storm. Real bitter stuff too.
Qt has been around for quite a while but picked up stream considerably, especially in the last year. Whomever uses it really likes it. It is moving beyond the confines of a UI class library as well, their users are looking actively for solutions to common programming tasks that start with the letter Q. That's a powerful vote of confidence.
But if you are on a Microsoft stack, none of these class libraries is where the real UI development is at. WPF is the elephant in the room, it's capabilities are a hundred miles beyond what's listed above. Its ability to break device and paradigm boundaries are powerful, writing code that runs on a desktop as well as a web browser as well as a phone is hard to beat. But C++ is not part of that.
|
3,121,378 | 3,122,968 | A tricky counter - just a int, but he won't work as requested | I'm near the end of a program I had got to code for my university courses, but I got into a last trouble: formatting the output!
It's nothing about code: this is just cosmetics (but I need to fix that cause my output's got to respect some standards).
Basically, my program will read a .csv file and process that by dividing the resulting graph into clusters. I want to have them numbered, no matter how (I don't care if it starts with 2 instead of 1 as long as the numbers are correct ofc). Problem is I can't figure out how to do that O-o
I've already got a proper data structure to handle my clustering activity: every node of the graph points to some list. If I have n clusters, I'll have n lists. The lists are instanced inside the Vertex class and the algorithm will merge them during runtime, so I can't number them as simply as I would, were they in a vector or something.
So now I have, say, n lists. I can start easily by looking at the 1st vertex (they're in the vector V) and following the pointer.
After doing that, I'm in the first list. I can move on it and get every node it points to that list, and I'd want my program to put a "1" on that inside the map.
Then I'd look inside V for another vertex whose list is different from before, and again get to the list and save the nodes with "2" and so on.
My counter doesn't work properly: asking for 3 clusters on a .csv file, the output was like this:
c 1 1
c 2 1
c 3 1
c 4 1
c 5 1
c 6 5
c 7 1
c 8 1
c 9 1
c 10 1
c 11 1
c 12 5
c 13 5
c 14 1
c 15 1
c 16 1
c 17 1
c 18 17
c 19 17
c 20 17
c 21 17
c 22 5
c 23 17
c 24 17
c 25 17
c 26 17
c 27 17
c 28 17
c 29 17
c 30 17
c 31 5
c 32 5
Clusters labels are 1, 5, 17 instead of 1, 2, 3 lol U_U
map<int, int> clusterProcessor(Grafo &G, map_t &Map, int clusters, vector<Vertex*> &V {
map<int, int> clustermap;
list<Vertex*>::iterator listiter;
int j;
int counter = 1;
for (j=1; j < V.size(); ++j) {
if (V[j]->getMyset()->front() != V[j-1]->getMyset()->front())
counter++;
for (listiter = V[j]->getMyset()->begin(); listiter != V[j]->getMyset()->end();
listiter++)
clustermap.insert(pair<int, int> ( (*listiter)->id, counter) );
}
return clustermap;
}
void clusterPrinter(map<int, int> m) {
map<int, int>::iterator i;
for (i = m.begin(); i != m.end(); i++)
cout << "c " << i->first << " " << i->second << endl;
}
| Notice that the number is always the row number of the row right before it appears. This suggests that counter++ is always executing.
And sure enough, it is.
Perhaps you meant to compare the values of the first elements of each cluster, instead of the iterator addresses?
Based on the subsequent mapping you establish, I'd suggest changing
if (V[j]->getMyset()->front() != V[j-1]->getMyset()->front() ) counter++;
to
if (V[j]->getMyset()->begin()->id != V[j-1]->getMyset()->begin()->id) counter++;
|
3,121,454 | 3,122,720 | Is there a good library c/c++/java to generate video with special effects , transitions from a set of images? | I need to develop a video generator that takes in a set of images, music files and outputs mp4 videos. The platform is linux. Was wondering if there are any existing libraries that can do this job ?
Thanks
| I believe Processing can do what you want.
|
3,121,491 | 3,121,775 | What to do with proxy class copy-assignment operator? | Consider the following proxy class:
class VertexProxy
{
public:
VertexProxy(double* x, double* y, double* z)
: x_(x), y_(y), z_(z) {}
VertexProxy(const VertexProxy& rhs)
: x_(rhs.x_), y_(rhs.y_), z_(rhs.z_) {}
// Coordinate getters
double x() const {return *x_;}
double y() const {return *y_;}
double z() const {return *z_;}
// Coordinate setters
VertexProxy& x(double val) {*x_ = val; return *this;}
VertexProxy& y(double val) {*y_ = val; return *this;}
VertexProxy& z(double val) {*z_ = val; return *this;}
VertexProxy& operator=(const VertexProxy& rhs)
{
// Should it be this
x_ = rhs.x_; y_ = rhs.y_; z_ = rhs.z_;
// or this?
*x_ = *rhs.x_; *y_ = *rhs.y_; *z_ = *rhs.z_;
return *this;
}
private:
double* x_; double* y_; double* z_;
};
I need to be able to reset the proxy so that it holds different coordinate pointers (similarly to boost::shared_ptr.reset(). In addition, I would like to be able to assign the coordinate values to the ones from a different proxy ( i.e. proxy1.assign(proxy2) ).
What should be the meaning of operator= in my class above? To copy rhs's pointers (shallow copy) or rhs's values? Or should I just make operator= private and provide two members functions to avoid the ambiguity of operator=?
EDIT:
Ok, here's some background information. I'm writing a wrapper around a 3rd party GIS library (shapelib), which stores vertex coordinates (x,y,z,m) in separate arrays (instead of an array of structs). My proxy class is used to make this struct of arrays appear more like an array of structs. It works in tandem with a custom vertex iterator class that makes it much easier to work with ranges of vertices.
Shapelib handles the memory management. All my proxy class does is present a different "view" into the vertex data. When the user manipulates vertex coordinates using my proxy, it actually manipulates the vertex coordinates in the shapelib shape object.
| It's pretty simple. Do you want VertexProxy to act like a pointer, or a value? If you'd rather it acted like a pointer, then copy the pointers, if you'd rather it acted like a value, copy the values. Nobody can tell you that your class is a pointer or a value (especially since you seem to have something somewhat unusual). If you want better advice, we'd need to know what holds the actual doubles and why.
Quick edit:
Seems to me like actually, if you did the dereference, you'd have it acting like a reference or a pointer. However, the original point remains the same.
|
3,121,523 | 3,121,544 | C++: Construct subclass from base class instance? | I have three structs, one of which inherits from the other two:
typedef struct _abc
{
int A;
int B;
int C;
} ABC;
typedef struct _def
{
int D;
int E;
int F;
} DEF;
typedef struct _abcdef : ABC, DEF { } ABCDEF;
(I want the third struct to contain all the members of the first two. Is there a better way to do it?)
Now, I have fully populated instances of ABC and DEF, and I want to make a new ABCDEF instance:
int main()
{
ABC abc;
abc.B = 2;
abc.C = 1;
abc.A = 10;
DEF def;
def.D = 32;
def.E = 31;
def.F = 90;
// make a new ABCDEF with all the values of abc and def
}
What is the best way to create the ABCDEF? I could do this, but it kinda sucks:
ABCDEF abcdef;
abcdef.A = abc.A;
abcdef.B = abc.B;
abcdef.C = abc.C;
abcdef.D = def.D;
abcdef.E = def.E;
abcdef.F = def.F;
The above is coupled to the members of the structs, and is messy if many members are added.
| This is C++. Those typedefs aren't needed. And you have constructors:
struct abc {
int A;
int B;
int C;
abc(int a, int b, int c) : A(a), B(b), C(c) {}
};
struct def {
int D;
int E;
int F;
def(int d, int e, int f) : D(d), E(e), F(f) {}
};
struct abcdef : abc, def {
abcdef(const abc& a, const def& d) : abc(a), def(d) {}
};
int main()
{
abc a(2,1,10);
def d(32,31,90);
abcdef ad(a,d);
return 0;
}
|
3,121,716 | 3,121,888 | Generating Java binding to a Qt based library | I'm writing a Qt based (QtCore) C++ library and would like to have access to it from Java and Python. Python is not a problem because of PySide and SIP. But I can't seem to find any information about doing the same with Java. The fact that Java bindings exist for Qt makes me hopefuly that there is a way to create bindings for a custom Qt based library.
Has anyone done this? Or have any information or pointers on how this can be done?
| Qt Jambi included a generator that you could use on your own Qt classes.
However, Nokia discontinued support for Jambi after v4.5.
For technical details, see http://doc.qt.nokia.com/qtjambi-4.5.0_01/com/trolltech/qt/qtjambi-generator.html .
Also, there's an early white paper still at http://www.sra.co.jp/qt/relation/qtjambi-whitepaper-tp3.pdf with details of the generator in chapter 4.
|
3,121,781 | 3,121,824 | Assigning value passed by reference to a member variable (in C++) | I am trying to wrap my head about scope in C++. Please consider the following:
class C
{
int i_;
public:
C() { i_ = 0;}
C(int i) { i_ = i; }
C(const C &c) {
i_ = c.i_;
cout << "C is being copied: " << i_ << endl;
}
int getI() { return i_; }
~C() {cout << "dstr: " << i_ << endl;}
};
class D
{
C c_;
public:
void setC(C &c) { c_ = c; }
int getC_I() { return c_.getI(); }
};
void Test(D &d)
{
C c(1);
d.setC(c);
//here c is going out of scope, surely it will be destroyed now?
}
int main()
{
D d;
Test(d); //this sets value of c_ to the local variable in Test.
//Surely this will be invalid when Test returns?
int ii = d.getC_I();
cout << ii << endl;
}
Running this program outputs:
dstr: 1
1
dstr: 1
Apparently, the first destructor call occurs in Test, and the other when program terminates and d is destroyed.
So my question is: Where was c copied? Is there fault with my reasoning? And general point I am trying to ask: is it safe to have a member function that takes a reference to an object and then stores it in a member variable?
Many thank for your help.
| Your code is fine as it stands right now. D::c_ is of type C rather than C &. Your SetC takes a reference to a C, and assigns the value referred to by that reference to C::c_, so what you have is an entirely separate C object that has the same value. Since you created d with automatic storage duration in main, it and c_ which is part of it remain valid until you exit from main.
|
3,121,799 | 3,121,834 | Automated testing of C++ console app in Visual Studio by sending text files to stdin? | I am going to take part in a coding contest my University is organizining next week.
I am only allowed to use C or C++ and I would prefer to use the latter one using Visual Studio 2010.
For every task there is a text input provided as plaintext to stdin, for example:
200 100 10
2 11
I need a tool which would assist me with running my code with some pre-defined text file as stdin input.
On a unix-based system I would just use something like:
gcc mycode.cpp
./mycode.o <test1.in >result1.out
diff result1.out test1.out
Is there any way to reach this in Visual Studio 2010.
Or maybe one could recommend a nice C++ IDE with rich debugging functions which would have something like this "out of the box"?
With best regards,
Alexander.
| You can do essentially the same thing with the Visual Studio compiler and the Windows command line:
cl /EHsc mycode.cpp
mycode.exe <test1.in >result1.out
fc result1.out test1.out
Though you might want a better diff tool than fc.
You can also code up your code so the routine that does the real work is called with stream handles (or some other mechanism to get and put the data) and have a test build feed the data through files that it opens instead of stdin and stdout. When your testing is done, the real program simply calls that routine with the stdin and stdout handles.
There are unit test frameworks for C++ that might help you with that, but getting one of them installed and integrated in might be more trouble than just writing your own simple test jig.
|
3,121,843 | 3,121,874 | C++ template argument inference and string literals | I have a "set" data type:
template <class V>
struct Set {
void add(const V& value) {}
};
I want to write a top-level function version of Set::add.
template <class V>
void add(const Set<V>& set, const V& value) {}
This doesn't quite work with string literals:
Set<const char*> set;
const char* val = "a";
set.add(val); // ok
set.add("a"); // ok
add(set, val); // ok
add(set, "a"); // ERROR
add<const char*>(set, "a"); // ok
The error message (g++ 4.2.4):
no matching function for call to ‘add(Set<const char*>&, const char [2])’
It looks it has something to do with the fact that "a" has type const char[2] and not const char*. Does anybody know how to get this to work?
| The problem is that V gets one type for the left parameter, and another type for the right one. I suspect you also want to be able to say add(setOfLong, 0) - but with that template you couldn't. I recommend to add a separate template parameter to solve this
template <class SetV, class V>
void add(const Set<SetV>& set, const V& value) {}
|
3,122,155 | 3,122,261 | std::map assignment of read only location | I have a static std::map<std::string, CreateGUIFunc> in a class that basically holds strings identifying gui types, and CreateGUIFunc is a reference to a factory function.
In my constructor I have
if ( m_factoryRef.size() == 0 ) {
m_factoryRef["image"] = &CreateGUI<Image>;
m_factoryRef["button"] = &CreateGUI<Button>;
}
...
However, this gives me an error saying assignment of read-only location ‘GUIManager::m_factoryRef.std::map<_Key, _Tp, _Compare, _Alloc>::operator[] [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = GUI*(), _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, GUI*()> >](((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)(& std::basic_string<char, std::char_traits<char>, std::allocator<char> >(((const char*)"image"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>())))))))’|
I'm not sure why this is a read-only assignment. I also tried changing it to a normal member just to see if maybe it had to do with it being static, but same thing.
What is the problem?
Edit: Some definitions to make things a bit more clear
// these are all private
typedef GUI* CreateGUIFunc();
template<class T>
GUI* GUIManager::CreateGUI( std::string &filepath, int x, int y ) {
return new T( filepath, x, y );
}
static std::map<std::string, CreateGUIFunc> m_factoryRef;
P.S. If there is any cleaner way to initialize a static map please let me know.
| In C++, typedef GUI* CreateGUIFunc(); isn't a function with unspecified parameters, it's a function with NO parameters. So none of your functions match that type. What you want is typedef GUI* (*CreateGUIFunc)( std::string &filepath, int x, int y );
Next, try using the insert member function of the map instead of the subscript operator, that way you can't end up calling the constant version by accident.
|
3,122,284 | 3,122,361 | In which case is if(a=b) a good idea? |
Possible Duplicate:
Inadvertent use of = instead of ==
C++ compilers let you know via warnings that you wrote,
if( a = b ) { //...
And that it might be a mistake that you certainly wanted to write:
if( a == b ) { //...
But is there a case where the warning should be ignored, because it's a good way to use this "feature"?
I don't see any code clarity reason possible, so is there a case where it’s useful?
| Two possible reasons:
Assign & Check
The = operator (when not overriden) normally returns the value that it assigned. This is to allow statements such as a=b=c=3. In the context of your question, it also allows you to do something like this:
bool global;//a global variable
//a function
int foo(bool x){
//assign the value of x to global
//if x is equal to true, return 4
if (global=x)
return 4;
//otherwise return 3
return 3;
}
...which is equivalent to but shorter than:
bool global;//a global variable
//a function
int foo(bool x){
//assign the value of x to global
global=x;
//if x is equal to true, return 4
if (global==true)
return 4;
//otherwise return 3
return 3;
}
Also, it should be noted (as stated by Billy ONeal in a comment below) that this can also work when the left-hand argument of the = operator is actually a class with a conversion operator specified for a type which can be coerced (implicitly converted) to a bool. In other words, (a=b) will evaulate to true or false if a is of a type which can be coerced to a boolean value.
So the following is a similar situation to the above, except the left-hand argument to = is an object and not a bool:
#include <iostream>
using namespace std;
class Foo {
public:
operator bool (){ return true; }
Foo(){}
};
int main(){
Foo a;
Foo b;
if (a=b)
cout<<"true";
else
cout<<"false";
}
//output: true
Note: At the time of this writing, the code formatting above is bugged. My code (check the source) actually features proper indenting, shift operators and line spacing. The <'s are supposed to be <'s, and there aren't supposed to be enourmous gaps between each line.
Overridden = operator
Since C++ allows the overriding of operators, sometimes = will be overriden to do something other than what it does with primitive types. In these cases, the performing the = operation on an object could return a boolean (if that's how the = operator was overridden for that object type).
So the following code would perform the = operation on a with b as an argument. Then it would conditionally execute some code depending on the return value of that operation:
if (a=b){
//execute some code
}
Here, a would have to be an object and b would be of the correct type as defined by the overriding of the = operator for objects of a's type. To learn more about operator overriding, see this wikipedia article which includes C++ examples: Wikipedia article on operator overriding
|
3,122,344 | 3,122,369 | Boost C++ regex - how to get multiple matches | If I have a simple regex pattern like "ab." and I have a string that has multiple matches like "abc abd". If I do the following...
boost::match_flag_type flags = boost::match_default;
boost::cmatch mcMatch;
boost::regex_search("abc abd", mcMatch, "ab.", flags)
Then mcMatch contains just the first "abc" result. How can I get all possible matches?
| You can use the boost::sregex_token_iterator like in this short example:
#include <boost/regex.hpp>
#include <iostream>
#include <string>
int main() {
std::string text("abc abd");
boost::regex regex("ab.");
boost::sregex_token_iterator iter(text.begin(), text.end(), regex, 0);
boost::sregex_token_iterator end;
for( ; iter != end; ++iter ) {
std::cout<<*iter<<'\n';
}
return 0;
}
The output from this program is:
abc
abd
|
3,122,382 | 3,122,393 | Using volatile long as an atomic | If I have something like this...
volatile long something_global = 0;
long some_public_func()
{
return something_global++;
}
Would it be reasonable to expect this code to not break (race condition) when accessed with multiple threads? If it's not standard, could it still be done as a reasonable assumption about modern compilers?
NOTE: ALL I'm using this for is atomic increment and decrement - nothing fancier.
| No - volatile does not mean synchronized. It just means that every access will return the most up-to-date value (as opposed to a copy cached locally in the thread).
Post-increment is not an atomic operation, it is a memory access followed by a memory write. Interleaving two can mean that the value is actually incremented just once.
|
3,122,440 | 3,122,483 | What do you call a single header whose purpose is to include other header files? | I've seen this done before in various C++ libraries - namely Qt (QtCore, QtGui, etc.) and Irrlicht (irrlicht.h):
// file - mylibrary.h
#include "someclass1.h"
#include "someclass2.h"
#include "someclass3.h"
// and so on...
Obviously this exists for convenience - a programmer wishing to use the library only has to include one header instead of lots of different ones. My question is, is there a special name for this type of header file? Even if there's not an "official" name, what you you refer to it as? A "convenience header" or "module header" or something?
Names given so far (with sources):
Convenience header (Boost)
Master header (Apple Official Documentation, An MSDN blog)
Meta-header (The Game Programming Wiki)
User contributions (no sources):
Header header (Larry Watanabe)
Umbrella header (Chuck)
| That's a nice question :)
I've found some sources that call it master header file, e.g:
Apple Official Documentation
An MSDN blog
When it is used to host headers for the header precompiler, it could be called precompiler global header:
http://www.rfoinc.com/docs/qnx/watcom/compiler-tools/cpheader.html
However I don't think that there's a single widespread way to call it.
|
3,122,475 | 3,129,280 | How do I get the giomm-2.4 package? | I am trying to build a GTK application (c++) using NetBeans. After including the gtkmm.h file I had to use the pkg-config tool to determine what it's dependencies where. I then added them to the included folders. Netbean complains that it cannot find 'giomm-2.4'. This package does not exist in /usr/lib and I cannot seem to find this package in Synaptic.
Can someone tell me where to find it?
Thanks.
| Try this package: libglibmm-2.4-dev.
|
3,122,530 | 3,122,563 | understanding Functors in STL | quoting from "The C++ Standard Library" by N M Jousttis, Section 5.9
#include < iostream>
#include < list>
#include < algorithm>
using namespace std;
//function object that adds the value with which it is initialized
class AddValue {
private:
int the Value; //the value to add
public:
//constructor initializes the value to add
AddValue(int v) : theValue(v) { }
//the "function call" for the element adds the value
void operator() (int& elem) const { elem += theValue; }
};
int main()
{
list<int> coll;
for (int i=1; i<=9; ++i)
coll.push_back(i);
//The first call of for_each() adds 10 to each value:
for_each (coll.begin(), coll.end(), AddValue(10)) ;
Here, the expression AddValue(10) creates an object of type AddValue that is initialized with
the value 10. The constructor of AddValue stores this value as the member theValue. Inside
for_each(), "()" is called for each element of coll. Again, this is a call of operator () for
the passed temporary function object of type AddValue. The actual element is passed as an
argument. The function object adds its value 10 to each element. The elements then have the
following values:
after adding 10:
11 12 13 14 15 16 17 18 19
The second call of for_each() uses the same functionality to add the value of the first element
to each element. It initializes a temporary function object of type AddValue with the first element
of the collection:
for_each (coll.begin(), coll.end(), AddValue (*coll. begin()) ) ;
The output is then as follows after adding first element:
22 23 24 25 26 27 28 29 30
what I don't understand is in the second case why is the output is not
22 34 35 36 37 38 39 40 41
meaning is a new functor being created for each call or is the functor used for each call ?
| The expression AddValue(*coll. begin()) creates one temporary object of class AddValue. That temporary is then passed to the for_each function. for_each then calls the object's function call operator - that is, operator() - once for each element from coll.begin() to coll.end().
Technically, for_each takes the functor parameter by value (not reference), so a it actually operates on a copy of the temporary, not the temporary itself.
|
3,122,600 | 3,122,624 | Radio style instead of MF_CHECKED for menu item? | I noticed some applications have a blue circular instead of a checkmark which MF_CHECKED produces. Which style produces this circular one?
Thanks
| Check out the MFT_RADIOCHECK menu type flag...
|
3,122,619 | 3,123,707 | Migrating to Xcode and now having lots of "is not member of std" and some other header problems | I am migrating to OS X and now trying to use Xcode.
There is a project that was compiling and running normally on a g++ linux distro, now on mac it is returning a thousand of errors. I guess that the linux std files, somehow included others files needed and now they are not this connected in the std of Mac OS X.
How can I know what I am doing wrong, like here:
/Users/Jonathan/Development/C++/Josk/Var.h:257:0 No match for 'operator<<' in 'out << ((Josk::Var*)Jv)->Josk::Var::ToString()' in /Users/Jonathan/Development/C++/Josk/Var.h
the code is:
friend ostream& operator << (ostream &out, Josk::Var &Jv){
out << Jv.ToString();
return out;
}
I don't know what to add here to solve this,
here are the actual includes:
#include <iostream>
#include <ostream>
#include <typeinfo>
#include <map>
#include <utility>
#include <algorithm>
Thanks!
Jonathan
| It looks like you're missing #include <string>.
|
3,122,667 | 3,129,740 | Construct OpenCV element type in runtime | In OpenCV, when I need to create a cv::Mat, I will need to do something along the line of
cv::Mat new_mat(width, height, CV_32FC3)
What happens if I only know that I need the elements to be either float or double + whether I need 1/2/3 channels in runtime?
In other words, given the element type (float) and number of channel (int), how can I construct the term: CV_32FC3?
| Read the source for cxtypes.h. It contains lines like the following:
#define CV_32FC1 CV_MAKETYPE(CV_32F,1)
#define CV_32FC2 CV_MAKETYPE(CV_32F,2)
#define CV_32FC3 CV_MAKETYPE(CV_32F,3)
#define CV_32FC4 CV_MAKETYPE(CV_32F,4)
#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n))
#define CV_64FC1 CV_MAKETYPE(CV_64F,1)
#define CV_64FC2 CV_MAKETYPE(CV_64F,2)
#define CV_64FC3 CV_MAKETYPE(CV_64F,3)
#define CV_64FC4 CV_MAKETYPE(CV_64F,4)
#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))
CV_MAKETYPE is defined as:
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))
This suggests the following code:
bool isdouble;
int nchannels;
// ...
if (isdouble) typeflag = CV_64FC(nchannels);
else typeflag = CV_32FC(nchannels);
I haven't tested this; let me know if it works. Also: I hate opencv's terrible type safety.
|
3,122,678 | 3,122,689 | how can a pixel in a bitmap can be deleted? | i m decreasing the resolution of a bitmap. i found a method on a site which is as follows
Average the values of all surrounding pixels, store that value in the choosen pixel location, then delete all the surrounding pixels.so a 4*6 matrix becomes a 4 x 3 matrix.
i am accessing pixels by this code
for(int y = 0; y < bmp.bmHeight; y++)
{
for(int x = 0; x < bmp.bmWidth; x++)
{
COLORREF rgb = dc.GetPixel(x, y);
BYTE r = GetRValue(rgb);
BYTE g = GetGValue(rgb);
BYTE b = GetBValue(rgb);
dc.SetPixel(x, y, RGB(r,g,b));
}
}
tell me how can i delete a pixel?
| You can't really delete a pixel, a bitmap is a matrix of pixels. Rather, you should make a new bitmap of the intended size, and copy pixels into that.
|
3,122,695 | 3,122,743 | What is an efficient way to wrap HWNDs in objects in C++? | I have been working with C++ and Win32 (non MFC/ATL) I am playing around with writing my own class library to wrap certain Win32 objects (HWNDs in particular).
When it comes to creating windows, I find the "RegisterClassEx / CreateWindowEx" method very awkward. This design makes it hard to write simple class wrappers (one must resort to thunks, or TLS or some other complicated mechanism).
It seems to me it would have been simpler to just let the application specify the window procedure and a user-data pointer at window creation time.
Is there any obvious reason I'm missing for the design choice here? Is there a really simple and efficient way for this to work?
| ATL's CWindow and CWindowImpl are your friends.
CWindowImpl makes takes care of the RegisterClass/CreateWindow awkwardness that you speak of.
CWindow is a basic "wrapper" class for an HWND with all the win32 functions abstracted out.
The reason I prefer ATL over MFC. ATL is a very lightweight set of classes with all the source code provided. It's a simple #include with no extra libraries or runtimes to deal with. After rolling my own WndProcs and window encapsulation classes for many years, I've found CWindowImpl a joy to work with. You have to declare a global AtlModuleExe instance in your code to use it, but besides that, ATL stays out of the way.
Links to documenation for these classes below:
CWindow:
http://msdn.microsoft.com/en-us/library/d19y607d.aspx
CWindowImpl:
http://msdn.microsoft.com/en-us/library/h4616bh2.aspx
Update: Here's some sample code I dug up for you:
class CMyApp : public CAtlExeModuleT<CMyApp>
{
public:
static HRESULT InitializeCom()
{
CoInitialize(NULL);
return S_OK;
}
};
CMyApp g_app;
class CMyWindow : public CWindowImpl<CMyWindow>
{
public:
CMyWindow();
~CMyWindow();
BEGIN_MSG_MAP(CMyWindow)
MESSAGE_HANDLER(WM_PAINT, OnPaint);
MESSAGE_HANDLER(WM_CLOSE, OnClose);
END_MSG_MAP();
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled);
};
LRESULT CMyWindow::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled)
{
// your WM_PAINT code goes here
}
LRESULT CMyWindow::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& fHandled)
{
PostQuitMessage();
}
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdline, int nCmdShow)
{
// 640x480 window
CMyWindow appwindow;
RECT rect = {0, 0, 640, 480};
RECT rectActual = {0};
appwindow.Create(NULL, rect, L"App Window", WS_OVERLAPPEDWINDOW);
appwindow.ShowWindow(SW_SHOW);
{
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// app shutdown
appwindow.DestroyWindow();
return 0;
}
|
3,122,901 | 3,123,355 | non-copying istringstream | So istringstream copies the contents of a string when initialised, e.g
string moo("one two three four");
istringstream iss(moo.c_str());
I was wondering if there's a way to make std::istringstream use the given c_str as its buffer without copying things. This way, it won't have to copy large bits of memory before passing the std::istringstream& to functions that take istream& as an argument.
What I've been trying to do is convert some functions which only take std::ifstream& arguments (they're mostly parsers) into taking istream& as well. Would I have to make my own istream subclass for this?
| It's fairly trivial to write a basic std::streambuf class that reads from a given memory area. You can then construct an istream from this and read from that.
initializing a C++ std::istringstream from an in memory buffer?
Note that the lifetime of the buffer pointed to be c_str() is very limited, though, and there's no guarantee that a call to c_str() want cause some copying although I don't know of any implementations where it does.
|
3,123,196 | 3,123,516 | need help in contrast stretching | i have found this formula and its description on a site
l(x,y)=(l(x,y)-min)(no of intensity levels/(max-min)) + initial intensity level
where, I( x,y ) represents the images, on the left side it represents the output image, while on the right side it represents the xth pixel in the yth column in the input image. In this equation the "min" and "max" are the minimum intensity value and the minimum intensity value in the current image. Here "no. of intensity levels" shows the total number of intensity values that can be assigned to a pixel. For example, normally in the gray-level images, the lowest possible intensity is 0, and the highest intensity value is 255. Thus "no. of intensity levels" is equal to 255.
i have converted it into code, have i correctly converted it?
for(int y = 0; y < bmp.bmHeight; y++)
{
for(int x = 0; x < bmp.bmWidth; x++)
{
COLORREF rgb = dc.GetPixel(x, y);
BYTE r = GetRValue(rgb);
BYTE g = GetGValue(rgb);
BYTE b = GetBValue(rgb);
BYTE p,p1;
if(r<g)
{
p=r;
p1=g;
}
else
{
p=g;
p1=r;
}
if(b<p)
p=b;
if(b>p1)
p1=b;
BYTE bw = (RGB(r, g, b)-p);
bw=bw*(255/(p1-p));
bw+=p1;
dc.SetPixel(x, y, RGB(bw, bw, bw));
}
| This is my attempt to code the formula. Based on the formula from Fisher et al. Note that you will still run into artificial looking images unless you use the cutoff fraction described in Fisher's article, but that is your own homework ;-)
I didn't test this with real images, debugging it is also your homework.
Reference:
For calculation of the intensity, see HSL and HSV on wikipedia.
typedef unsigned char byte;
const byte OUT_MIN = 0; // The desired min output luminosity 0 to stretch to entire spectrum
const byte OUT_MAX = 255; // The desired max output luminosity 255 to stretch to entire spectrum
byte min = 255, max = 0;
// get the minimum and maximum values.
for( int y = 0; y < bmp.bmHeight; y++ )
{
for( int x = 0; x < bmp.bmWidth; x++ )
{
COLORREF rgb = dc.GetPixel(x, y);
byte intensity = ( rValue(rgb) + gValue(rgb) + bValue(rgb) ) / 3;
min = min < intensity ? min : intensity;
max = max > intensity ? max : intensity;
}
}
// set the new pixel values
for(int y = 0; y < bmp.bmHeight; y++)
{
for(int x = 0; x < bmp.bmWidth; x++)
{
COLORREF rgb = dc.GetPixel(x, y);
// Creates color image
// Calculate new color using the formula. Has to be int, not byte, because you might go out of range.
// We correct the range manually on the next two lines.
int r = ( rValue( rgb ) - min ) * ( OUT_MAX / (max - min) ) + OUT_MIN;
r = r < 0 ? 0 : r;
r = r > 255 ? 255 : r;
int g = ( gValue( rgb ) - min ) * ( OUT_MAX / (max - min) ) + OUT_MIN;
g = g < 0 ? 0 : g;
g = g > 255 ? 255 : g;
int b = ( bValue( rgb ) - min ) * ( OUT_MAX / (max - min) ) + OUT_MIN;
b = b < 0 ? 0 : b;
b = b > 255 ? 255 : b;
dc.SetPixel( x, y, RGB( r, g, b ) );
}
}
|
3,123,328 | 3,123,517 | Delete a Binary Tree with a Stack | I'm still working on my binary trees, and the insertion, lookup, maximum, minimum functions are all working great so far. So I want to do a deletion function next. I included a Stack which saves- ah hell, I'll just show the code:
class Tree
{
private:
int value_;
Tree *root_;
Tree *left_;
Tree *right_;
std::stack<Tree*> treeStack;
The delete function:
int Tree::eraseTree()
{
while( !treeStack.empty() )
{
Tree *temp = treeStack.top();
treeStack.pop();
delete temp;
}
if( treeStack.empty() )
return 1;
else
return -1;
}
I'm getting errors now. This wouldn't be much of a problem- I try to debug my own code- except this time it's telling me there is an error in the <deque> library file which I am not even using.
Before the program shuts off I get System.AccessViolationException and the faulty code points to the deque file. Of course it can't be there, it has to be some pointer in my code. Which leads me to believe I am not working the stack correctly, or not pushing to the stack correctly.
What am I doing wrong here? Am I actually deleting the nodes when I call .pop on the stack?
EDIT:
if( !root_ )
{
root_ = new Tree(val, 0, 0);
treeStack.push(root_);
return val;
}
And
Tree *parent = findInsertionPoint(val, root_);
if( val < parent->value_ )
parent->left_ = new Tree(val, 0, 0);
else
parent->right_ = new Tree(val, 0,0);
treeStack.push(parent);
return val;
Is where I am pushing my elements on the stack.
Additional Question: Does a std::stack have to be built in the ctor?
| You're crashing in deque because the stack contains one of those. If you look at the stack trace after the crash, then you can find out what your code was doing when it happened.
It looks like the final snippet of code is putting the wrong node on the stack; surely it should be the newly created node, not the insertion point? If you add two nodes to a parent, then the parent will end up in the stack twice, and will be deleted twice.
It should probably be more like
Tree *parent = findInsertionPoint(val, root_);
Tree *child = new Tree(val, 0, 0);
if( val < parent->value_ )
parent->left_ = child;
else
parent->right_ = child;
treeStack.push(child);
return val;
But I'd favour DeadMGs suggestion to use smart pointers for left_ and right_ (but don't make root_ an auto_ptr, if that's shared by all the nodes), and let them clean up for you. I'm not sure I see the point of the stack; if it's to speed up the tree's destruction, then ask yourself two questions before adding a complex and error-prone optimisation:
is it slow enough to be worth the development/debugging cost of optimising?
is it worth the extra runtime and memory cost of building and maintaining the stack alongside the tree?
And your additional question: the stack will be built in the constructor, but you don't have to write any code to do it. Its default constructor will be called automatically, and that will give you a usable, empty stack.
Also, unless this is a learning exercise, you should use std::multiset rather than reinventing it.
|
3,123,340 | 3,123,528 | PyS60 vs Symbian C++ | I'm planning some Symbian related development on S60 3.1 platform. It seems like generally available language options are Python and C++. However Nokia's official forum seems very much tilted towards C++.
I want to know what are the advantages and disadvantages of using Python for S60 over Symbian C++? And is it even possible to do Python programming for S60 3.1 platform?
| PyS60 is good when you need to prototype something simple fast. If you try to develop a full application with it though, you'll most likely find yourself sooner or later wanting to use features that are available in Symbian C++ but not in PyS60 without writing bindings (in C++) for it. Also you'll need to deal with the right version of PyS60 runtime being available, and some of them aren't backwards compatible.
If you go for the Symbian C++ route, you can embed a python interpreter in it too.
|
3,123,479 | 3,123,584 | How do I fit a variable sized char array in a struct? | I don't understand how the reallocation of memory for a struct allows me to insert a larger char array into my struct.
Struct definition:
typedef struct props
{
char northTexture[1];
char southTexture[1];
char eastTexture[1];
char westTexture[1];
char floorTexture[1];
char ceilingTexture[1];
} PROPDATA;
example:
void function SetNorthTexture( PROPDATA* propData, char* northTexture )
{
if( strlen( northTexture ) != strlen( propData->northTexture ) )
{
PROPDATA* propPtr = (PROPDATA*)realloc( propData, sizeof( PROPDATA ) +
sizeof( northTexture ) );
if( propPtr != NULL )
{
strcpy( propData->northTexture, northTexture );
}
}
else
{
strcpy( propData->northTexture, northTexture );
}
}
I have tested something similar to this and it appears to work, I just don't understand how it does work. Now I expect some people are thinking "just use a char*" but I can't for whatever reason. The string has to be stored in the struct itself.
My confusion comes from the fact that I haven't resized my struct for any specific purpose. I haven't somehow indicated that I want the extra space to be allocated to the north texture char array in that example. I imagine the extra bit of memory I allocated is used for actually storing the string, and somehow when I call strcpy, it realises there is not enough space...
Any explanations on how this works (or how this is flawed even) would be great.
| Is this C or C++? The code you've posted is C, but if it's actually C++ (as the tag implies) then use std::string. If it's C, then there are two options.
If (as you say) you must store the strings in the structure itself, then you can't resize them. C structures simply don't allow that. That "array of size 1" trick is sometimes used to bolt a single variable-length field onto the end of a structure, but can't be used anywhere else because each field has a fixed offset within the structure. The best you can do is decide on a maximum size, and make each an array of that size.
Otherwise, store each string as a char*, and resize with realloc.
|
3,123,699 | 3,123,780 | C++ multiple operator overloads for the same operator | I know I can answer this question easily for myself by generatin the code and see if it compiles. But since I couldn't find a similar question, I thought it's knowledge worth sharing.
Say I am overloading the + operator for MyClass. Can I overload it multiple times. Different overload for different types. Like this:
class MyClass{
...
inline const MyClass operator+(const MyClass &addend) const {
cout<<"Adding MyClass+MyClass"<<endl;
...//Code for adding MyClass with MyClass
}
inline const MyClass operator+(const int &addend) const {
cout<<"Adding MyClass+int"<<endl;
...//Code for adding MyClass with int
}
...
};
int main(){
MyClass c1;
MyClass c2;
MyClass c3 = c1 + c2;
MyClass c4 = c1 + 5;
}
/*Output should be:
Adding MyClass+MyClass
Adding MyClass+in*/
The reason I want to do this is that I am building a class that I want to be as optimized as possible. Performance is the biggest concern for me here. So casting and using switch case inside the operator + overloaded function is not an option. I f you'll notice, I made both the overloads inline. Let's assume for a second that the compiler indeed inlines my overloads, then it is predetermined at compile time which code will run, and I save the call to a function (by inlining) + a complicated switch case scenario (in reality, there will be 5+ overloads for + operator), but am still able to write easily read code using basic arithmetic operators.
So, will I get the desired behavior?
| The canonical form of implementing operator+() is a free function based on operator+=(), which your users will expect when you have +. += changes its left-hand argument and should thus be a member. The + treats its arguments symmetrically, and should thus be a free function.
Something like this should do:
//Beware, brain-compiled code ahead!
class MyClass {
public:
MyClass& operator+=(const MyClass &rhs) const
{
// code for adding MyClass to MyClass
return *this;
}
MyClass& operator+=(int rhs) const
{
// code for adding int to MyClass
return *this;
}
};
inline MyClass operator+(MyClass lhs, const MyClass& rhs) {
lhs += rhs;
return lhs;
}
inline MyClass operator+(MyClass lhs, int rhs) {
lhs += rhs;
return lhs;
}
// maybe you need this one, too
inline MyClass operator+(int lhs, const MyClass& rhs) {
return rhs + lhs; // addition should be commutative
}
(Note that member functions defined with their class' definition are implicitly inline. Also note, that within MyClass, the prefix MyClass:: is either not needed or even wrong.)
|
3,123,939 | 3,123,972 | Thread Local Storage | When you allocate some TLS for thread A in a slot, can you then access that same slot from Thread B?
Is it internally synchronized or how does that work?
| The local variables of a function are unique to each thread that runs the function. This can be accomplished with help of TLS which as already mentioned is local for each thread.
If you want to share some data between threads there are several options starting from using global or static variables up to memory mapped files and etc... also check thread synchronization if you need to share data between threads.
The following diagram illustrates how TLS works.
For more details check MSDN.
(source: microsoft.com)
|
3,123,980 | 3,123,991 | Explanation of ambiguity in function overloading for this example in C++ | I'm reading Stroustrup's book, the section on overloading and related ambiguities.
There's an example as follows:
void f1(char);
void f1(long);
void k(int i)
{
f1(i); //ambiguous: f1(char) or f1(long)
}
As the comment states, the call is ambiguous.
Why?
The previous section in the book stated 5 rules based on matching formal and actual parameters. So shouldn't the above function call come under rule 2, regarding "promotions"?
My guess was that 'i' should be promoted to a long, and that's that.
As per the comment, it seems that a int to char conversion (a demotion?) also comes under rule 2?
| Anything goint from int above isn't a promotion anymore. Anything going less than int to int is a promotion (except for rare cases - see below)
So if you change to the following it becomes non-ambiguous, choosing the first one
void f1(int);
void f1(long);
void k(unsigned short i) {
f1(i);
}
Notice that this is only true on platforms where int can store all values of unsigned short. On platforms where that is not the case, this won't be a promotion and the call is ambiguous. On such platforms, the type unsigned int will be the promotion target.
Sort of the same thing happens with floating points. Converting float to double is a promotion, but double to long double isn't a promotion. In this case, C++ differs from C, where double to long double is a promotion likewise (however, it doesn't have overloading anyway).
|
3,124,015 | 3,124,027 | Weird auto-initialization behavior | I learned that auto-variables aren't initialized to zero. So the following code will behave correctly and prints random numbers on the screen:
#include <iostream>
using std::cout;
using std::endl;
void doSomething()
{
int i;
cout << i << endl;
}
int main()
{
doSomething();
}
But why won't this snipped behave in the same way ?
#include <iostream>
using std::cout;
using std::endl;
void doSomething()
{
int i;
cout << i << endl;
}
int main()
{
int j;
cout << j << endl;
doSomething();
}
This snippet shows:
0
0
Does anyone know why "j" and "i" were suddenly initialized to zero here?
| Using an uninitialized variable is undefined behaviour. It's likely you wouldn't get the same behaviour on another compiler. The only 'why' is to be found inside the source code to your specific C++ compiler.
|
3,124,066 | 3,124,077 | Is it safe if a virtual function refers to variable in a derived class in C++? | When derived is cast back into base.
By safe, I mean it works properly for known c++ compiler.
It seems to be working for VIsual C++ 2008.
E.g
class zero
{
virtual int v()=0;
}
class a: public zero
{
public:
int value;
a(int vin)
{
value =vin;
}
int v()
{
return value;
}
}
zero *e1= new a(3);
cout << e1->v();
| It is safe and fully correct behaviour. That is the reason why you have virtual or pure virtual methods. Most of the time you will want to hide implementation details and manipulate objects through their interface (or pure virtual class). That is standard and all C++ compilers must support it.
|
3,124,082 | 3,124,111 | How can I pass a variable from class element to class element? (C++) | My question might not be too correct... What I mean is:
class MyClass
{
public:
MyClass()
{
}
virtual void Event()
{
}
};
class FirstClass : public MyClass
{
string a; // I'm not even sure where to declare this...
public:
FirstClass()
{
}
virtual void Event()
{
a = "Hello"; // This is the variable that I wish to pass to the other class.
}
};
class SecondClass : public MyClass
{
public:
SecondClass()
{
}
virtual void Event()
{
if (a == "Hello")
cout << "This is what I wanted.";
}
};
I hope that this makes at least a little sense...
Edit: _This changed to a.
| What you need to do is make SecondClass inherit from FirstClass and declare _This as protected.
class FirstClass : public MyClass
{
protected:
string _This;
public:
and
class SecondClass : public FirstClass
What you got doesn't make sense because classes can only see members and functions from their parents (MyClass in your case). Just because two class inherit from the same parent does not mean they have any relation or know anything about each other.
Also, protected means that all classes that inherit from this class will be able to see its members, but nobody else.
|
3,124,094 | 3,124,158 | Do rvalue references allow implicit conversions? | Is the following code legal?
std::string&& x = "hello world";
g++ 4.5.0 compiles this code without any problems.
| This is discussed on usenet currently. See Rvalue reference example in 8.5/3 correct or wrong?.
It's not legal.
|
3,124,307 | 3,124,320 | Inlined constructors? Explain this behavior[C++] | Consider this code
#include <iostream>
#include <cstdio>
using namespace std;
class Dummy {
public:
Dummy();
};
inline Dummy::Dummy() {
printf("Wow! :Dummy rocks\n");
}
int main() {
Dummy d;
}
All is good here!
Now I do this modification. I move the declaration of Dummy to "dummy.h".
class Dummy {
public:
Dummy();
};
And define the constructor Dummy() as following in "dummy.cpp"
#include "dummy.h"
inline Dummy::Dummy() {
printf("Wow! :Dummy rocks\n");
}
And finally, I have my main file as:
#include <iostream>
#include <cstdio>
#include "dummy.h"
using namespace std;
int main() {
Dummy d;
}
It compiles fine, but I get a linker error complaining an undefined reference to Dummy::Dummy().
Any insights.
--
| You have to put all inline functions (including methods and constructors/destructors) in a header file, where they are declared.
Though this code should work either way, with main() calling the constructor as if the inline keyword was not there. Are you sure you are passing object files from both compilation units to the linker?
|
3,124,328 | 3,124,336 | C++ : iterating the vector | I'm very new to C++ and I'm trying to learn the vector in C++..
I wrote the small program as below. I like to foreach(var sal in salaries) like C# but it doesn't allow me to do that so I googled it and found that I have to use iterator.. Im able to compile and run this program but I dont get the expected output.. I'm getting "0 0 0 0 0 0 1 2 3 4 5 6 7 8 9" instead of "0 1 2 3 4 5 6 7 8 9"..
Could anyone please explain me why? Thanks.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void show(int i)
{
cout << i << " ";
}
int main(){
vector<int> salaries(5);
for(int i=0; i < 10; i++){
salaries.push_back(i);
}
for_each(salaries.begin(), salaries.end(), show);
}
| You created a vector with 5 elements, then you push 10 more onto the end. That gives you a total of 15 elements, and the results you're seeing. Try changing your definition of the vector (in particular the constructor call), and you'll be set. How about:
vector<int> salaries;
|
3,124,467 | 3,124,494 | Tool to identify the similarities in logic between a function of C and C++ | Is there a tool in either Linux/Windows that would enable us to determine if a logic of the particular function in C is same as that of a particular function in C++ ?
| In general, the equivalence of Turing machines is undecidable, so no.
|
3,124,595 | 3,124,638 | Multiple declaration for function | I have a function declared in my base class and specified as virtual, I am trying to re-declare it in a derived class but I'm getting a multiple declaration error.
Anyone know if I'm missing something here?
class Field {
public:
virtual void display() = 0;
virtual int edit() = 0;
virtual bool editable() const = 0;
virtual void *data() = 0;
virtual Field *clone() const = 0;
};
class LField : public Field {
int rowNum;
int colNum;
int width;
char *val;
bool canEdit;
int index;
public:
virtual void *data() { return val; }
};
class IVField : public LField {
void (*ptrFunc)(void *);
bool (*ptrValid)(int &);
int *data;
public:
void* data() {
return data;
}
};
class DVField : public LField {
int decimalsToDisplay;
double *data;
void (*ptrFunc)(void *);
bool (*ptrValid)(double&);
public:
void* data() {
return data;
}
};
| You have a function named data and a member variable named data in the same class. That's not allowed. Pick a different name for your member variable.
You also appear to be re-declaring many member variables. That's probably not what you want to do. If you want to declare them in the base class and use them in descendants, then they should probably have protected visibility. The default visibility for classes, when you haven't specified any other, is private, which means, for example, that descendants of IVField (such as DVField) cannot access the ptrFunc variable you declared in IVField. The ptrFun variable you declared in DVField has absolutely no relation to the one declared in the parent class. Make the IVField one protected, and then descendants don't need to duplicate the declaration for themselves.
You're also going to have to implement all those other abstract methods before the compiler will allow you to instantiate any of those classes.
|
3,124,729 | 3,124,756 | Where in memory are variables stored in C++? | If I have code like this:
int e;
int* f;
int main() {
int a, b, c;
int* d;
}
Where in memory are these variables stored?
And, what's the problem with defining global variables (out of a function, like main in this case)?
| a,b,c and d will exist on the stack. If you were to create an instance of an int (with malloc or new), that would go on the heap - but the pointer called 'd' would still exist on the stack.
e and f are allocated space in the memory space of the app, in the so-called 'Data segment' - see:
http://en.wikipedia.org/wiki/Data_segment
You also asked about stack size: that's configured by the compiler, see here:
http://msdn.microsoft.com/en-us/library/tdkhxaks(VS.71).aspx
|
3,124,837 | 3,124,945 | Multithreading in C++ ... where to start? | I'd like to start learning multithreading in C++. I'm learning it in Java as well. In Java, if I write a program which uses multithreading, it will work anywhere. However in C++, doesn't multithreading rely on platform-specific API's? If so, that would seem to get in the way of portability.
How can I do multithreading in C++ without causing portability issues? Is boost's thread library a good solution?
As a sidenote - how is it even possible to implement multithreading as a library? Isn't that something that has to be done by the compiler?
| If you do not have a compiler that supports C++0x yet (available with visual studio c++ 2010 for example), use boost threads. (Unless you use a framework that already supports threading, which is not the case - you wouldn't ask the question otherwise -). These boost threads became actually the standard in the brand new C++. Before that time C++ itself was thread unaware.
TBB Threading Building Blocks might also be interesting to you if you want to learn other aspects in parallel programming.
Regarding Qt: if you only want threading support it is complete overkill. It has horribly slow round trip times from compiling to result. It is really well designed thought. But not an official standard like the C++0x threads from boost. Therefore I would not take it as a first choice.
|
3,124,990 | 3,125,007 | Clear an Array to NULL without knowing the type | I have to create a function that can take in an array of pointers with a known size, and set all the pointers to NULL. The caveat is that I don't know the type beforehand. This is what I have tried so far:
template <typename T>
static void Nullify(T** _Array, int _Size, unsigned int _SizeOf)
{
for (int i = 0; i < _Size; i++)
{
_Array[i * _SizeOf] = NULL;
}
}
Which is giving me errors (not the function itself, but I am trampling on memory I should not be trampling on resulting in a memory error later on). I am passing in the array (_Array - already initialized to _Size), its size (_Size), and the sizeof(Pointer*) as _SizeOf.
Any help would be greatly appreciated :)
| You don't need _SizeOf. This is what you want:
template <typename T>
static void Nullify(T** _Array, int _Size)
{
for (int i = 0; i < _Size; i++)
{
_Array[i] = NULL;
}
}
The compiler knows the size of a pointer, and does the math for you during the array dereference.
|
3,125,003 | 3,125,035 | Two dimensional arrays allocation problem | this is an interview question my friend was asked yesterday. The question was something like: will this program crash with an "access violation" error or not? I looked at it for a while and thought no, it won't. But actually trying this out in visual studio proved me wrong. I cannot figure out what happens here... or to be more precise, i know what happens, but do not understand WHY. The problem seems to be that the matrix2 array does not get allocated at all.
Code below:
#include <iostream>
#include <ctime>
using namespace std;
int** matrixAlloc( const int rows, const int cols );
void matrixAlloc( int** matrix, const int rows, const int cols );
void matrixDealloc( int** m, const int rows);
void matrixPrint( const int* const * const m, const int rows, const int cols );
int main( int argc, char** argv )
{
srand( (unsigned int)time( NULL ) );
int** matrix1 = matrixAlloc( 4, 5 );
matrixPrint( matrix1, 4, 5 );
matrixDealloc( matrix1, 4 );
int ** matrix2 = NULL;
matrixAlloc( matrix2, 4, 5 );
matrixDealloc( matrix2, 4 ); // <--- crash occurs here
}
int** matrixAlloc( const int rows, const int cols )
{
int **matrix = new int *[ rows ];
for ( int i = 0; i < rows; i++ )
{
matrix[ i ] = new int[ cols ];
for ( int j = 0; j < cols; j++ )
{
matrix[ i ][ j ] = (rand() * 12347) % 10;
}
}
return matrix;
}
void matrixAlloc( int** matrix, const int rows, const int cols )
{
matrix = new int *[ rows ];
for ( int i = 0; i < rows; i++ )
{
matrix[ i ] = new int[ cols ];
for ( int j = 0; j < cols; j++ )
{
matrix[ i ][ j ] = (rand() * 12347) % 10;
}
}
}
void matrixDealloc( int** matrix, const int rows )
{
for ( int i = 0; i < rows; i++ )
{
delete [] matrix[ i ];
}
delete [] matrix;
}
void matrixPrint( const int* const * const matrix, const int rows, const int cols )
{
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ )
{
cout << matrix[ i ][ j ] << " ";
}
cout << endl;
}
cout << endl;
}
| You are passing the double pointer "matrix2" by value. Therefore, when matrixAlloc finishes doing its thing, "matrix2" will still be whatever it was before the function was called. In order to get the change to populate, consider passing matrix2 by reference:
int** matrix2 = NULL;
matrixAlloc(&matrix2, 4, 5);
...
Don't forget to change the implementation of matrixAlloc to dereference matrix2 when necessary.
EDIT: Simple solution below. Change this line:
void matrixAlloc( int** matrix, const int rows, const int cols )
to this:
void matrixAlloc( int**& matrix, const int rows, const int cols )
|
3,125,090 | 3,126,467 | <string.h> conflicting with my own String.h | I have a project that was compiling ok within g++(I can't see the version right now) and now on xCode it is not.
I think that I got the problem now... I have a String.h file in my project and it seems tha the xCode compiler(that is gcc) is trying to add my own string file from the < cstring >... I am not sure of it, but take a look at this picture
http://www.jode.com.br/Joe/xCode1.png
from what it looks like, it is including my own instead of the system file, I was wondering... shouldn't #include < file > be a system include? because of the < > ? and shouldn't the system include a file within its own path and not the original path of my application?
As I said, I am not sure if this is what happening because I am just migrating to osx these past 2 days...
I was going to change my class and file name to not conflict, so it would work, if this is really the problem, but I was wondering, there should be another way to do this, because now my project isn't that big so I can do this in some time, but what if the project was bigger? it would be dificult to change all includes and class names...
Any help is appreciated
Thanks,
Jonathan
| Naming your headers with the same name as standard headers like string.h and including them simply with #include <String.h> is asking for trouble (the difference in casing makes no difference on some platforms).
As you said, however, it would be difficult to try to figure out what those are in advance when naming your headers. Thus, the easiest way to do this is to set to set your include path one directory level outside of a sub-directory in which your headers reside, ex:
#include <Jonathan/String.h>
Now you don't have to worry about whether the String.h file name conflicts with something in one the libraries you are using unless they happen to also be including <Jonathan/String.h> which is unlikely. All decent third-party libraries do this as well. We don't include <function.hpp> in boost, for instance, but instead include <boost/function.hpp>. Same with GL/GL.h instead of simply GL.h. This practice avoids conflicts for the most part and you don't have to work around problems by renaming String.h to something like Text.h.
|
3,125,136 | 3,125,156 | C++ header file question | I was trying out some c++ code while working with classes and this question occurred to me and it's bugging me a little.
I have created a header file that contains my class definition and a cpp file that contains the implementation.
If I use this class in a different cpp file, why am I including the header file instead of the cpp file that contains the class implementations?
If I include the class implementation file, then the class header file should be imported automatically right (since i've already included the header file in the implementation file)? Isn't this more natural?
Sorry if this is a dumb question, i'm genuinely interested in knowing why most people include .h instead of .cpp files when the latter seems more natural (I know python somewhat, maybe that's why it seems natural to me atleast). Is it just historical or is there a technical reason concerning program organisation or maybe something else?
| Because when you're compiling another file, C++ doesn't actually need to know about the implementation. It only needs to know the signature of each function (which paramters it takes and what it returns), the name of each class, what macros are #defined, and other "summary" information like that, so that it can check that you're using functions and classes correctly. The contents of different .cpp files don't get put together until the linker runs.
For example, say you have foo.h
int foo(int a, float b);
and foo.cpp
#include "foo.h"
int foo(int a, float b) { /* implementation */ }
and bar.cpp
#include "foo.h"
int bar(void) {
int c = foo(1, 2.1);
}
When you compile foo.cpp, it becomes foo.o, and when you compile bar.cpp, it becomes bar.o. Now, in the process of compiling, the compiler needs to check that the definition of function foo() in foo.cpp agrees with the usage of function foo() in bar.cpp (i.e. takes an int and a float and returns an int). The way it does that is by making you include the same header file in both .cpp files, and if both the definition and the usage agree with the declaration in the header, then they must agree with each other.
But the compiler doesn't actually include the implementation of foo() in bar.o. It just includes an assembly language instruction to call foo. So when it creates bar.o, it doesn't need to know anything about the contents of foo.cpp. However, when you get to the linking stage (which happens after compilation), the linker actually does need to know about the implementation of foo(), because it's going to include that implementation in the final program and replace the call foo instruction with a call 0x109d9829 (or whatever it decides the memory address of function foo() should be).
Note that the linker does not check that the implementation of foo() (in foo.o) agrees with the use of foo() (in bar.o) - for example, it doesn't check that foo() is getting called with an int and a float parameter! It's kind of hard to do that sort of check in assembly language (at least, harder than it is to check the C++ source code), so the linker relies on knowing that the compiler has already checked that. And that's why you need the header file, to provide that information to the compiler.
|
3,125,547 | 3,125,558 | Algorithms that can take an N length string and return a fixed size unique value? | I'm looking to add basic licensing to my application. I want to take in the user's name as a parameter and return a unique, fixed length code (sort of like MD5)
What are some algorithms that can do this?
Thanks
| The SHA algorithms should be decent for this (SHA-1, SHA-512, etc...). They are used in a lot of places where an MD5 could also be used but seem to be more well respected. I use them for password hashing, but sounds like their functionality as a 1-way hash would be good for this as well.
If you want fixed sized, you might then Base64 encode the resulting bytes and take the first N digits that you want. Even though you are losing some of the original hash, that should give you a large enough set of distinct possible keys that you are virtually impossible to get a repeat. As a frame of reference, this is a an example of a Base64 encoded UUID: "iFHqaiNjhTDpxp7ahBPX0A "
The possible result set of a UUID is so large that it is accepted practice to randomly generate them with the expectation that they are unique (I know this is surprising, but do a search).
|
3,125,552 | 3,125,660 | How to reverse data using an array of pointers (parse binary file) | I am parsing a binary file using a specification. The file comes in big-endian mode because it has streamed packets accumulated. I have to reverse the length of the packets in order to "reinterpret_cast" them into the right variable type. (I am not able to use net/inet.h function because the packets has different lengths).
The read() method of the ifstream class puts the bytes inside an array of chart pointers. I tried to do the reversion by hand using a but I cannot figure out how to pass the "list of pointers" in order to change their position in the array.
If someone knows a more efficent way to do so, please let me know (8gb of data needs to be parse).
#include <iostream>
#include <fstream>
void reverse(char &array[]);
using namespace std;
int main ()
{
char *a[5];
*a[0]='a'; *a[1]='b'; *a[2]='c'; *a[3]='d'; *a[4]='e';
reverse(a);
int i=0;
while(i<=4)
{
cout << *a[i] << endl;
i++;
}
return 0;
}
void reverse(char &array[])
{
int size = sizeof(array[])+1;
//int size = 5;
cout << "ARRAY SIZE: " << size << endl;
char aux;
for (int i=0;i<size/2;i++)
{
aux=array[i];
array[i]=array[size-i-1];
array[size-i-1]=aux;
}
}
Thanks all of you for your help!
| Not quite.
The file comes in big-endian mode because it has streamed packets accumulated. I have to reverse the length of the packets in order to "reinterpret_cast" them into the right variable type.
You need to reverse the bytes on the level of stored data, not the file and not the packets.
For example, if a file stores a struct.
struct S {
int i;
double d;
char c;
};
to read the struct you will need to reverse:
int: [4321]->[1234] // sizeof(int) == 4, swap the order of 4 bytes
double: [87654321]->[12345678] // sizeof(double) == 8, swap the order of 8 bytes
char: [1]->[1] // sizeof(char) == 1, swap 1 byte (no swapping needed)
Not the entire struct at once.
Unfortunately, it's not as trivial as just reversing the block of data in the file, or the file itself. You need to know exactly what data type is being stored, and reverse the bytes in it.
The functions in inet.h are used for exactly this purpose, so I encourage you to use them.
So, that brings us to c strings. If you're storing c strings in a file, do you need to swap their endianness? Well, a c string is a sequence of 1 byte chars. You don't need to swap 1 byte chars, so you don't need to swap the data in a c string!
If you really want to swap 6 bytes, you can use the std::reverse function:
char in[6] = get6bytes();
cout << in << endl; // shows abcdef
std::reverse(in, in+6);
cout << in << endl; // shows fedcba
If you're doing this on any large scale (a large amount of types), then you may want to consider writing a code generator that generates these byte swapping functions (and file reading functions), it's not too hard, as long as you can find a tool to parse the structs in c (I've used gcc-xml for this, or maybe clang would help).
This makes serialization a harder problem. If it's in your power, you may want to consider using XML or Google's protocol buffers to solve these problems for you.
|
3,125,582 | 3,125,855 | boost spirit qi numeric parsing of integer and floating points | i am trying to make sense of the following result. The test case code is
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/spirit/home/support/context.hpp>
#include <boost/spirit/home/phoenix.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
namespace sp = boost::spirit;
namespace qi = boost::spirit::qi;
using namespace boost::spirit::ascii;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
using phoenix::at_c;
using phoenix::push_back;
using phoenix::bind;
template <typename P>
void test_parser(
char const* input, P const& p, bool full_match = true)
{
using boost::spirit::qi::parse;
char const* f(input);
char const* l(f + strlen(f));
if (parse(f, l, p) && (!full_match || (f == l)))
std::cout << "ok" << std::endl;
else
std::cout << "fail" << std::endl;
}
int main() {
test_parser("+12345", qi::int_ ); //Ok
test_parser("+12345", qi::double_ - qi::int_ ); //failed, as expected
test_parser("+12345.34", qi::int_ ); // failed, as expected
test_parser("+12345.34", qi::double_ - qi::int_ ); //failed but it should be Ok!
};
the motivation here is that i want to match numbers '12345' as integers and NEVER as floating points. '12345.34' will match double_ and never int_ but the reciprocal case is not true; '12345' matches both integers (int_ ) and floating point (double_ ). I tried double_ - int_ and it successfully failed to match '12345'. However my hope was that the last test case '12345.34' would positively match double_ - int_, but the result i get is fail to match.
Why this is so, and how do i get a parser that only matches integers and another that only matches floating points (like in c, 5.0 would be interpreted as floating point)
| For your specific example, I think it's actually described in the Boost Spirit documentation under RealPolicies Specialization. To make things a bit easier for you, I whipped out a quick "real" parser, that only parses real numbers and not integers(or at least it worked with your simplified examples):
template <typename T>
struct strict_real_policies : qi::real_policies<T>
{
static bool const expect_dot = true;
};
qi::real_parser< double, strict_real_policies<double> > real;
And you can use this just like any other parser(like int_ and double_). You might have to add:
#include <boost/spirit/include/qi_numeric.hpp>
To get it to compile.
|
3,125,679 | 3,125,695 | Cross Platform File Exists & Read In C++ | How can I write two simple cross platform (Linux, Windows) functions for reading text file, and determine if some file exists?
I don't want to use a big library like Boost.IO for that. It's a very small plugin for some software and I don't think it's neccsary.
Thanks.
| The standard library should be sufficient. access will tell you if a file exists, and (if it's there) you can read with a normal std::ifstream.
|
3,125,702 | 3,125,758 | C++: Are YOU using Loki or Boost for functors ? | I've been reading Alexandrescu's book, Modern C++ design , and I've been quite impressed by the techniques he uses, so I wanted to add Loki library to my application.
However, after further investigation, I saw that boost, that I'm already using, provides a lot of similar functionality (not all though, I couldn't find a singleton in boost for example)
I was mostly interested in using loki because of the policy based design and the functors.
To me both, boost and loki have pros and cons. The main concern I have with loki is the poor documentation (the library isn't tied to the book anymore) but it seems to me that loki is more powerful and flexible than boost in some areas (I might be wrong on that one)
Before choosing to use boost or loki for functors and policies, I'd like to know the opinion of people who use them in real life.
Sometimes things look very good on paper but have some drawbacks when you use them for real:)
| I'm using Boost in my whole C++ environnement like an extension to the Standard Library (with VC9 and VC10).
I don't use it on all projects.
I use it on personal projects (mostly games) where I got full control of what are the dependencies.
I'm using boost::function in a big game project (with several other libraries from boost).
Loki is good too but I didn't feel the need. I think the only part of the library I'm thinking of using is the Singleton but I'm using a custom one that is fine enough for the moment.
|
3,125,715 | 3,125,755 | How can this compile? (delete a member of const object) | I would expect an error inside the copy constructor, but this compiles just fine with MSVC10.
class Test
{
public:
Test()
{
p = new int(0);
}
Test(const Test& t)
{
delete t.p; // I would expect an error here
}
~Test()
{
delete p;
}
private:
int* p;
};
| The issue that you are running into here is that you are not changing p per se (thus pstays immutable as you're not changing its value), but you're changing what p points to and thus are working at one additional level of indirection. This is possible because deleteing the memory associated with a pointer doesn't change the pointer itself.
In a strict sense the const-ness of the object is preserved, even though its logical constness has been violated as you pulled the rug from underneath whatever p was pointing to.
As JonH mentioned in the comment, if you were not able to delete the object pointed to by a pointer held in a const object, you would end up with memory leaks because you wouldn't be able to clean up properly after the object.
|
3,125,731 | 3,125,806 | private object pointer vs object value, and returning object internals | Related to: C++ private pointer "leaking"?
According to Effective C++ (Item 28), "avoid returning handles (references, pointers, or iterators) to object internals. It increases encapsulation, helps const member functions act const, and minimizes the creation of dangling handles."
Returning objects by value is the only way I can think of to avoid returning handles. This to me suggests I should return private object internals by value as much as possible.
However, to return object by value, this requires the copy constructor which goes against the Google C++ Style Guide of "DISALLOW_COPY_AND_ASSIGN" operators.
As a C++ newbie, unless I am missing something, I find these two suggestions to conflict each other.
So my questions are: is there no silver bullet which allows efficient reference returns to object internals that aren't susceptible to dangling pointers? Is the const reference return as good as it gets? In addition, should I not be using pointers for private object fields that often? What is a general rule of thumb for choosing when to store private instance fields of objects as by value or by pointer?
(Edit) For clarification, Meyers' example dangling pointer code:
class Rectangle {
public:
const Point& upperLeft() const { return pData->ulhc; }
const Point& lowerRight() const { return pData->lrhc; }
...
};
class GUIObject { ... };
const Rectangle boundingBox(const GUIObject& obj);
If the client creates a function with code such as:
GUIObject *pgo; // point to some GUIObject
const Point *pUpperLeft = &(boundingBox(*pgo).upperLeft());
"The call to boundingBox will return a new, temporary Rectangle object [(called temp from here.)] upperLeft will then be called on temp, and that call will return a reference to an internal part of temp, in particular, to one of the Points making it up...at the end of the statement, boundingBox's return value temp will be destroyed, and that will indirectly lead to the destruction of temp's Points. That, in turn, will leave pUpperLeft pointing to an object that no longer exists." Meyers, Effective C++ (Item 28)
I think he is suggesting to return Point by value instead to avoid this:
const Point upperLeft() const { return pData->ulhc; }
| The Google C++ style guide is, shall we say, somewhat "special" and has led to much discussion on various C++ newsgroups. Let's leave it at that.
Under normal circumstances I would suggest that following the guidelines in Effective C++ is generally considered to be a good thing; in your specific case, returning an object instead of any sort of reference to an internal object is usually the right thing to do. Most compilers are pretty good at handling large return values (Google for Return Value Optimization, pretty much every compiler does it).
If measurements with a profiler suggest that returning a value is becoming a bottleneck, then I would look at alternative methods.
|
3,125,742 | 3,125,749 | 'No matching function' -error when trying to insert to a set (c++) | I have the following code:
class asd {
public:
int b;
asd() { b = rand() % 10; }
bool operator<(asd &other) { return b < other.b; }
};
int main() {
asd * c; c = new asd();
set <asd> uaua;
uaua.insert(c);
}
Yet when running it, I get this error:
main.cpp|36|error: no matching function for call to ‘std::set<asd, std::less<asd>, std::allocator<asd> >::insert(asd*&)’|
I'm using g++ 4.4.3
Could someone please tell me where I'm going wrong? I've tried to crack this for a good while, but can't seem to find the solution. Thanks
| You have a set of asd, and you're trying to add a pointer.
Use:
asd c;
set <asd> uaua;
uaua.insert(c);
|
3,125,810 | 3,125,853 | Reading a number from file C++ | I have a file with a simple number, for example:
66
or
126
How can I read it to a int value in C++?
Note that the file may also contain some spaces or enters after the number.
I started like so:
int ReadNumber()
{
fstream filestr;
filestr.open("number.txt", fstream::in | fstream::app);
filestr.close()
}
How to continue?
Thanks.
| I don't really know why people are using fstream with set flags when he only wants to do input.
#include <fstream>
using namespace std;
int main() {
ifstream fin("number.txt");
int num;
fin >> num;
return 0;
}
|
3,125,872 | 3,125,878 | Unsigned Long Long Won't Go Beyond The 93th Fibonacci Number? | Here's the code I wrote for finding the n-th Fibonacci number:
unsigned long long fib(int n)
{
unsigned long long u = 1, v = 1, t;
for(int i=2; i<=n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}
While the algorithm runs pretty quickly, the output starts to freak out when n>93. I think/know it's because of the unsigned long long's 64bit size. I'm new to C++ but are there ways of getting around this so I can get the answer of something like fib(9999)?
Thanks
| http://gmplib.org/
GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.
The main target applications for GMP are cryptography applications and research, Internet security applications, algebra systems, computational algebra research, etc...
|
3,125,950 | 3,126,136 | C++ weird syntax spotted in Boost template parameters | I was having a look at the "Function" class documentation in Boost, and stumbled across this:
boost::function<float (int x, int y)> f;
I must admit this syntax is highly confusing for me. How can this be legal C++ ?
Is there any trick under the hood ? Is this syntax documented anywhere?
| [Edit] This is an answer to the author's original, unedited question which was actually two questions.
I must admit this syntax is highly
confusing for me. How can this be
legal C++ ? :) Is there any trick
under the hood ? Is this syntax
documented anywhere ?
This is perfectly legal and it's actually not too complicated.
template <class T>
class C
{
public:
T* function_pointer;
};
void fn(int x)
{
cout << x << endl;
}
int main(int argc, char** argv)
{
C<void (int x)> c;
c.function_pointer = &fn;
c.function_pointer(123); // outputs x
}
It's basically the same thing as doing:
typedef void Function(int);
C<Function> c;
This type is not just applicable C++, it's just as applicable in C (the actual type C is parameterized to). The template magic here is taking something like the Function typedef here and being able to detect the types of the return values and arguments. Explaining that would be too lengthy here and boost::function uses a lot of the function traits meta-templates in boost to retrieve that information. If you really want to spend the time to learn this, you should try to understand the boost implementation starting with boost::function_traits in Boost.Type Traits.
However, I want to address your general problem. I think you are trying too hard to simplify a couple of lines of perfectly acceptable code. There's nothing wrong with passing the arguments for your command subclasses through their parameterized subclass constructors. Is is really worth trying to involve typelists and boost::function-like solutions here, thereby increasing compile times and code complexity significantly, just for that?
If you want to reduce it further, just write an execute function that will execute any command subclass and add it to the undo stack and so on:
typedef boost::shared_ptr<Command> CommandPtr;
void execute(const CommandPtr& cmd)
{
cmd->execute();
// add command to undo stack or whatever else you want to do
}
// The client can simply write something like this:
execute(CommandPtr(new CmdAdd(some_value) );
I really think the trade-off of trying to make it any more complicated isn't worth it. The boost authors wanted to write an extremely general-purpose solution for boost::function which would be used by many people across many platforms and compilers. However, they didn't try to generalize a command system capable of executing functions with different signatures across a unified undo system (thereby requiring the state of these commands to be preserved even after one is initially finished calling them and be able to undo and re-execute them without re-specifying the original state data on subsequent executions). For that, your inheritance-based approach is most likely the best and most straightforward one.
|
3,126,106 | 3,127,350 | What's the best way to have a variable number of template parameters? | Please consider this -probably poorly written- example :
class Command;
class Command : public boost::enable_shared_from_this<Command>
{
public :
void execute()
{
executeImpl();
// then do some stuff which is common to all commands ...
}
// Much more stuff ...
private:
virtual void executeImpl()=0;
// Much more stuff too ...
};
and :
class CmdAdd : public Command
{
public:
CmdAdd(int howMuchToAdd);
void executeImpl();
int _amountToAdd;
};
// implementation isn't really important here ....
With this, I can simply add a callback using this syntax :
boost::shared_ptr<Command> cmdAdd(CmdAdd(someValue));
cmdAdd->execute();
It works flawlessly. My "Command" class does much more things which are common to all commands, such as implementing undo, redo, progress report and so on, but I removed it from the code for the sake of readability.
Now my question is simple :
is there a way to rewrite the command class, so that I can replace this call :
boost::shared_ptr<Command> cmdAdd(CmdAdd(someValue));
cmdAdd->execute();
by something like :
CmdAdd(someValue); // preferably
or CmdAdd->execute(someValue)
I've been thinking about that a lot but I have a conceptual problem :
I wanted to template my Command class like
template <typename R,typename T1, typename T2, ..., typename Tn> class Command
{
R1 execute(T1 p1, ...,Tn pn)
{
return executeImpl(T1 p1, ...,Tn pn);
// then do some stuff which is common to all commands ...
}
}
but obviously, there's a problem here :
the syntax template <typename R,typename T1, typename T2, ..., typename Tn> isn't legal C++ , AFAIK.
Do I have to write n versions of Command, like :
template <typename R> class Command
template <typename R,typename T1> class Command
template <typename R,typename T1, typename T2> class Command
...
and so on ?
(not even sure this is gonna work indeed)
Or is there another, more elegant way to do this ?
Is the syntax, mentioned here of any use there ? (function f;)
I've been looking at Loki's type lists and they seem to do the job. But I can't find anything that in Boost. I read on the web that boost::mpl is what one wants to use to implement typelists, but I'm a bit confused by MPL docs ?
Any insights on this ?
Regads,
D.
| Interesting question :)
First of all, there is an issue you overlooked: you need a common base class for all Command and this class cannot be templated if you are going to use a stack of them (for undo/redo).
Therefore you are stuck with:
class Command
{
public:
void execute();
private:
virtual void executeImpl() = 0;
};
I can understand your desire an execute function with parameters, but don't forget that anyway you would need to save those parameters for the undo/redo operation. It's just simpler to get them through the constructor.
However, you could still use a templated method to actually invoke a command:
template <class Command>
void execute() { Command cmd; cmd.execute(); }
template <class Command, class T0>
void execute(T0& arg0) { Command cmd(arg0); cmd.execute(); }
/// ...
int main(int argc, char* argv[])
{
execute<MyLittleCommand>("path", 3);
}
Which is close to the syntax you desired. Note that I have purposely forgotten about the stack here, in my mind you need to pass it to the execute method for registration (once completed).
Not that I would also probably change the Command design to get closer to a Strategy pattern:
struct CommandImpl
{
virtual ~CommandImpl();
virtual void executeImpl() = 0;
};
class Command
{
public:
template <class C>
static Command Make() { return Command(new C()); }
template <class C, class T0>
static Command Make(T0& arg0) { return Command(new C(arg0)); }
/// ....
void execute(CommandStack& stack)
{
mImpl->executeImpl();
stack.Push(*this);
}
private:
Command(CommandImpl* c): mImpl(c) {}
boost::shared_ptr<CommandImpl> mImpl;
};
It's the typical combination of Non Virtual Interface and Pointer to Implementation idioms.
|
3,126,141 | 3,126,245 | Getting text from tab control item is failing | I'm trying to get the text from a tab control like this:
TCITEM itm;
itm.mask = TCIF_TEXT;
TabCtrl_GetItem(engineGL.controls.MainGlTab.MainTabHwnd,i,&itm);
but the psztext part of the structure is returning a bad pointer (0xcccccccccc).
I create the tabs like this:
void OGLMAINTAB::AddTab( char *name )
{
TCITEM itm;
itm.cchTextMax = 30;
itm.pszText = name;
itm.mask = TCIF_TEXT;
int numitems = TabCtrl_GetItemCount(MainTabHwnd);
SendMessage(MainTabHwnd,TCM_INSERTITEM,numitems,(LPARAM)&itm);
}
why is it not returning the text as I want it to?
Thanks
| When setting the text, cchTextMax is ignored.
When getting the text, you need to provide your own buffer and set cchTextMax accordingly. (Note that when the message returns, you need to use the itm.pszText pointer and not your own buffer since the control will sometimes change the pszText member to point to its internal buffer)
|
3,126,448 | 3,126,455 | Install my compiled libs in the system to be used by an executable | I am using Xcode and, after some struggling, it is compiling my dynamic libraries okie dokie for now.
My kinda-problem now is that I need to use those libs with another project, that is an executable.
I would like that Xcode, after compiling my libs, copy them to the executable folder, or, better, copy the libs to a system directory, where they would be loaded without having to compile(thus copying) the libs over again
There is a Install Directory in the project's settings, the default is /usr/local/lib, but I don't even have a folder called local at /usr (I tried to reach it through the terminal), so I guess this isn't working at all...
any help is appreciated!
Thanks,
Jonathan
| Perhaps the "Copy Files" build phase can do this for you. Select "Absolute Path" and then maybe "only when installing".
Ah, so here's the documentation you want (first section after intro, "Build Locations"):
http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/210-Building_Products/building.html
Though if you want the libraries installed in the "install location" even when doing debug builds, then the "Copy Files" build phase might end up being better.
Haven't done this myself but those are the things that come to mind directly.
|
3,126,463 | 3,128,320 | Handling large scale dataset | From the online discussion groups and blogs, I have seen a lot of interview questions are related to handling large scale dataset. I am wondering is there a systematic approach to analyze this type of questions? Or in more specific, is there any data structure or algorithms that can be used to deal with this? Any suggestions are really appreciated.
| "Large-scale" data sets fall into several categories that I've seen, each of which presents different challenges for you to think about.
Data that's too big to fit in memory. Here, some key techniques are:
Caching data that's frequently used for better performance
Working on data from a file a chunk at a time instead of trying to read the whole file into memory at once (if you're not working sequentially through the file, this can be particularly challenging!)
Distributing data across the memory of several machines.
Data that's too big to fit into a single file because of file system or hardware architecture limits. This is pretty easy to solve – split the file – but there's a practical question in many cases of what a sensible split would be.
Data that's too big to fit on a single hard disk. Here, mostly the techniques are to buy bigger disks :-), or to distribute the data across several machines.
Distributing data across multiple machines poses interesting challenges when you need to do analysis or transformations on the data. This is a deep topic with a lot of different approaches and challenges. Map/reduce frameworks like CouchDB and Hadoop have recently become popular tools for research and application in this area.
Data that's too big for a single database instance. This can be a problem of disk size (ran out of space) or performance (memory cache keeps getting blown, indices have simply gotten too big). Maintaining robustness and performance of data split across multiple DB instances, potentially in multiple data centers, is an area of perennial interest to large enterprises. Here, the choices are:
Vertical splits (different tables to different DBs)
Horizontal splits (same table on different DBs, but holding different data)
Other problems often associated with large-scale data sets, but not size-related problems per se, are:
Data that is coming in fast. Think of systems that need to scale to millions or even billions of transactions per minute.
Data that is constantly changing. How do you deal with stale data or data that's being modified while you're working on it?
|
3,126,646 | 3,540,788 | Please suggest a user-mode filesystem filter framework | I need a user-mode filesystem filter (not virtual filesystem). One of such frameworks is http://eldos.com/cbflt/, but it has some bugs and I need an alternative.
Can you please suggest similar frameworks.
| CallbackFilter is the only filter driver solution available. You mention dokan and fuse, but they are not filters, they are file system drivers (like Callback File System). This is a very different thing.
If you have problems with CallbackFilter, please report them to tech.support and we will address the issues ASAP.
|
3,126,664 | 3,127,289 | Function doesnt want to take my argument? | A friend sent me his threading class.
Now I just want to run a listener but the thread doesnt want to accept the function.
I want to execute the function (defined in static class Networks) THREAD listen(void* args). THREAD is a #define THREAD unsigned __stdcall
Networks::init() {
listenerth = thread();
listenerth.run(listen, NULL, "listener");
}
In class thread he defined run as void run( THREAD func(void*), void* args, const char* pname);
How can I get that to run listen in another thread either?
[edit]
Error message:
main.cpp(19): error C3867: 'Networks::listen': function call missing argument list; use '&Networks::listen' to create a pointer to member
But when i move my mouse to the error place(symbol listen), it shows me this in a tooltip(yes, MS VC++):
unsigned int __stdcall
Networks::listen(void* data)
Error: argument of type "unsigned int
(__stdcall Networks::*)(void *data)"
is incompatible with parameter of type
"unsigned int (__stdcall )(void)"
| As others say, you can't use a non-static member function here, because it expects a normal function pointer. If you need to call a non-static member (because it needs to access state in the class), then you could use the args argument to call it via a static "trampoline" function, something like this:
unsigned listen() {/* do the interesting stuff */}
static THREAD call_listen(void* me)
{
return static_cast<Networks*>(me)->listen();
}
void init()
{
listener = thread();
listener.run(call_listen, this, "listener");
}
|
3,126,669 | 3,126,688 | When to Return a Recursive Function? | I have a question on return and recursive functions.
This is again based off of a binary Tree which I am currently working on. The code is
void Tree::display()
{
if( !root_ )
return;
display_r(root_);
}
void Tree::display_r(Tree *node)
{
if( 0 == node )
return;
display_r(node->left_);
std::cout << node->value_ << std::endl;
display_r(node->right_);
}
This is working code. Compiles and runs without fail, printing the numbers from smallest to largest. However, this did not used to be so.
The code above was first written with
return display_r(node->left_);
std::cout << node->value_ << std::endl;
return display_r(node->right_);
which did not work. It simply returned without printing anything. Which makes sense, the return doesn't allow the code to move downwards.
This brought me to an interesting question. While writing the tree I was often wondering whether or not it was a good place to use return in a recursive function or not. Obviously, anytime the return is the last command executed in the block of code is okay to use. I think it's even okay to use in the display() function as
void Tree::display()
{
if( !root_ )
return;
return display_r(root_);
}
So my question is: when do I know for sure I can use return, and when shouldn't I use it? Are there gray areas where it's up to me to decide what's best, and is there a safety-net? As in, "When in doubt, don't use returns in a recursive function?"
Thanks!
| I suggest studying the return keyword more carefully and also practicing recursion a bit more.
return display_r(node->left_);
// this following code would not be executed in your example,
// you've already returned out of the function!
std::cout << node->value_ << std::endl;
return display_r(node->right_);
Here the return is necessary:
if( 0 == node )
return;
... as this is the base case (aka general solution) for your recursive algorithm. When you encounter a null for a child, you stop, otherwise continue. Note that this code is part of an if statement. It is only executed in certain circumstances (precisely the circumstance for which you want to prematurely return out of the function and stop recursing).
In your particular case you could also write this without using return at all, and very easily:
void Tree::display_r(Tree *node)
{
if (node) // equivalent to if (node != 0)
{
display_r(node->left_);
std::cout << node->value_ << std::endl;
display_r(node->right_);
}
}
As an aside, and without meaning to offend, it looks as though you are borrowing from examples without quite understanding how they work. Try to think for yourself and play with the code and try to understand it. If need be, put a comment next to every instruction indicating what it does in a way that's understandable to you.
Also do try to learn the debugger; I can't emphasize this enough. A lot of university students go through their whole undergraduate degree without being taught how to use a debugger, and that's a real shame. It should be one of the first things taught! Tracing through your code with a debugger will really help you to see the behavior of the code that you write. If you aren't being taught how to use it, I recommend learning how to use it for yourself. It will show you how the machine goes through every line of code you write, step-by-step.
|
3,126,795 | 3,126,810 | C++ looking for String.Replace() | i have a a char array in C++ which looke like {'a','b','c',0,0,0,0}
now im wrting it to a stream and i want it to appear like "abc " with four spaces insted of the null's
i'm mostly using std::stiring and i also have boost.
how can i do it in C++
basicly i think im looking for something like
char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually...
std::string newString(hellishCString, sizeof(hellishCString));
newString.Replace(0,' '); // not real C++
ar << newString;
| Use std::replace:
#include <string>
#include <algorithm>
#include <iostream>
int main(void) {
char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually...
std::string newString(hellishCString, sizeof hellishCString);
std::replace(newString.begin(), newString.end(), '\0', ' ');
std::cout << '+' << newString << '+' << std::endl;
}
|
3,126,806 | 3,126,854 | When embedding Java in a C++ application, which files do I need to take? | Our C++ application hosts Sun's JVM and I need to upgrade it to the newest version on Windows. I downloaded JDK 6u20, but I have no idea which folders to take into our installation. We currently have some version of Java 5 but it seems that whoever did it in the first place, cherry picked the files.
I'd like to know which folders to take from the installation of JDK. We are using JNI so I will also need all the include files/libs.
Also, the Java people are saying that I should take the files from JDK installation rather than the JRE, is there any difference? Maybe in the jars that ship in the JDK's JRE?
| Without knowing your application, it's not possible to say which files can be left out, so I'd say use the entire JRE.
However, you can find out which files the original creator of the installer didn't select by comparing the installer's JRE files with the original JRE. You can then write up these files and take a guess as to why they are not needed by your application.
If in doubt, leave it in. :)
EDIT: The JRE redistribution license requires the software to be complete:
(a) you distribute the Software complete and unmodified and only
bundled as part of Your applets and applications ("Programs"),
See http://java.sun.com/javase/6/webnotes/install/jre/README
However, the same document also mentions that the files are divided into required and optional files, and lists which files are optional. So, you can leave out the optional files.
|
3,126,918 | 3,126,966 | parse variable from php to a c++ function as an argument | I have a web server which receives an image from a client and do some SIFT based image matching at the server (win32) end send the result back to the client.
Receiving image is done using apache and php. SIFT based processing functions are in C++. Now I want to parse the data in php variable $image (the variable which holds the received image) to the main function of C++ program as an argument.
Then I want to take the result back to php code. Result is the matching number of points (integer value)
|
save the image to a file. you may use file_put_contents...
use system('cpp_program "/path/to/image"') function to run the program.(or does it take image data as an argument? that would be strange). these functions return the console output of the run program.
that's what i would do:
$tmpFileName = tempnam();
file_put_contents($tmpFileName, $image);
$cppProgramResult = intval(trim(system('cpp_program "'.$tmpFileName.'"')));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.