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 |
|---|---|---|---|---|
2,489,406 | 2,489,421 | Best Practice - Validating Input In Simple GUI Application? | I'm writing a GUI app with wxwidgets in C++ for one of my programming classes. We have to validate input and throw custom exceptions if it doesn't meet certain conditions. My question is, what is best practice when it comes to this? Should I write a seperate function that checks for errors, and have my event handler's call that function? Or should I do my error-checking in my event handlers? Or does it really matter?
Thanks!
| Throwing exceptions for this seems a little odd.
I've always felt that a GUI app should prevent invalid data from even being entered in a control, which can be done using event handlers. For data that is inconsistent between several controls on a form, that should be validated when OK is pressed or whatever, and if the data isn't OK, prevent the form from closing and indicate the error.
The validation can also be done prior to pressing OK, but it shouldn't prevent the data being entered, only indicate the problem (and perhaps disable the OK button until its fixed). Basically, the inconsistent value entered in this control may not be inconsistent once the user has edited the value in the next control he's moving on to.
Try to avoid message boxes for reporting these errors - a status bar or a read-only text control within the form is better.
A function/method should be defined that does all the consistency checks for the form, but it shouldn't throw an exception. Bad input isn't the "exceptional" case from typical users - it happens all the time, especially when I'm the user. More to the point, you should only use exceptions when error-handling would otherwise mess up the structure of your code, which shouldn't be the case in an "is the data in this form OK - yes, fine, accept and close" event handler.
The function should just return an error code to indicate which error to report - or report the error itself and return an error flag.
Not so long ago, wxWidgets wasn't even exception-safe - IIRC, you still have to enable exception-safety as an option when you build the library.
|
2,489,533 | 2,492,941 | What would be the safest way to store objects of classes derived from a common interface in a common container? | I'd like to manage a bunch of objects of classes derived from a shared interface class in a common container.
To illustrate the problem, let's say I'm building a game which will contain different actors. Let's call the interface IActor and derive Enemy and Civilian from it.
Now, the idea is to have my game main loop be able to do this:
// somewhere during init
std::vector<IActor> ActorList;
Enemy EvilGuy;
Civilian CoolGuy;
ActorList.push_back(EvilGuy);
ActorList.push_back(CoolGuy);
and
// main loop
while(!done) {
BOOST_FOREACH(IActor CurrentActor, ActorList) {
CurrentActor.Update();
CurrentActor.Draw();
}
}
... or something along those lines. This example obviously won't work but that is pretty much the reason I'm asking here.
I'd like to know: What would be the best, safest, highest-level way to manage those objects in a common heterogeneous container? I know about a variety of approaches (Boost::Any, void*, handler class with boost::shared_ptr, Boost.Pointer Container, dynamic_cast) but I can't decide which would be the way to go here.
Also I'd like to emphasize that I want to stay away as far as possible from manual memory management or nested pointers.
Help much appreciated :).
| As you have guessed you need to store the objects as pointers.
I prefer to use the boost pointer containers (rather than a normal container of smart pointers).
The reason for this is the boost ptr container access the objects as if they were objects (returning references) rather than pointers. This makes it easier to use standard functors and algorithms on the containers.
The disadvantage of smart pointers is that you are sharing ownership.
This is not what you really want. You want ownership to be in a single place (in this case the container).
boost::ptr_vector<IActor> ActorList;
ActorList.push_back(new Enemy());
ActorList.push_back(new Civilian());
and
std::for_each(ActorList.begin(),
ActorList.end(),
std::mem_fun_ref(&IActor::updateDraw));
|
2,489,582 | 2,489,624 | implementing ioctl() commands in FreeBSD | I am adding some code to an existing FreeBSD device driver and I am trying to pass a char* from user space to the driver. I've implemented a custom ioctl() command using the _IOW macro like so: #define TIBLOOMFILTER _IOW(0,253,char*)
My call looks something like this:
int file_desc = open("/dev/ti0", O_RDWR);
ioctl(file_desc, TIBLOOMFILTER, (*filter).getBitArray());
close(file_desc);
When I call ioctl() I get: Inappropriate ioctl for device as an error message. Any guess as to what may be doing wrong? I've defined the same macro in my device driver, and added it to the case statement.
| Did you register your ioctl handler with
.d_ioctl = ioctl_handler
in ?devsw (char/block device switch table)?
|
2,489,613 | 2,489,700 | How To Get System Folder Path(C:\Windows C:\Program Files) in Windows using C++? | I am programming in c++ MFC,
I want to get "C:\windows" "c:\program files" folder path.
Sometimes user may setup windows in other folder such as c:\windows0.
Is there any API to get absolute path of the windows and program files path?
Many thanks!
| Using Win32 API>
For the Windows folder:
TCHAR windir[MAX_PATH];
GetWindowsDirectory(windir, MAX_PATH);
For program files:
TCHAR pf[MAX_PATH];
SHGetSpecialFolderPath(
0,
pf,
CSIDL_PROGRAM_FILES,
FALSE );
Where MAX_PATH comes from the Windows headers and will guarantee the buffer is long enough for the longest (non-UNC) path.
Also, note that SHGetSpecialFolderPath can be used to retrieve other "special" folder including the Windows folder just by replacing the third parameter to any from this list.
|
2,489,627 | 2,489,683 | Setting minimum number of decimal places for std::ostream precision | Is there a way to set the "minimum" number of decimal places that a std::ostream will output?
For example, say I have two unknown double variables that I want to print (values added here for the sake of illustration):
double a = 0;
double b = 0.123456789;
I can set my maximum decimal precision so that I output b exactly
std::cout << std::setprecision(9) << b << std::endl;
>>> 0.123456789
Is there a way to set a "minimum" precision (a minimum number of decimal places), while retaining the "maximum" precision, so that
std::cout << a << std::endl << b << std::endl;
yields
0.0
0.123456789
not
0
0.123456789
?
Thanks!
Phil
the short answer to this is "No". The stream has only one precision setting, with no facility to differentiate between maximum and minimum precision. Thanks all for your generous advice!
| I do not think there is a way to achieve what you are asking without turning the number into a string (with high precision), and stripping off the trailing zeros.
This is appropriate, because just because there are trailing zeros doesn't mean there isn't precision there, and the run-time can't tell that.
For example, if I measure the weight of an object with a cheap scale, it may be 1.0 kgs.
If I weigh it with a high-accuracy scale, it may be 1.00000 kgs. Just because there are trailing zeros, doesn't mean that accuracy should be discarded.
|
2,489,833 | 2,489,885 | C++ : Math library that solve system of equations using back substitution algorithm | If I have this:
A * f = g;
A: upper triangular matrix (n x n)
f: (n x 1)
g: (n x 1)
Need to solve for f using back substitution algorithm. I would say that it not really that hard to write one myself, but oh well, if there is a library out there, then why not.
| Boost uBlas should work. At least if I understand your question correctly, you probably want to start by looking at lu_substitute() and inplace_solve().
|
2,489,914 | 2,489,922 | write application event information with Win32 API | .NET provides EventLog class that be able to write application event information to a particular log on the system. Is there simliar Win32 API that can be called with C++?
| I think you want Event Tracing for Windows:
http://msdn.microsoft.com/en-us/library/bb968803(VS.85).aspx
|
2,490,023 | 2,490,048 | How can I refactor this to use an inline function or template instead of a macro? | I have a useful macro here:
#include <algorithm>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <Windows.h>
namespace Path {
bool Exists(const std::wstring& path)
{
DWORD result = GetFileAttributesW(path.c_str());
return result != INVALID_FILE_ATTRIBUTES;
}
// THIS IS THE MACRO IN QUESTION!
#define PATH_PREFIX_RESOLVE(path, prefix, environment) \
if (boost::algorithm::istarts_with(path, prefix)) { \
ExpandEnvironmentStringsW(environment, buffer, MAX_PATH); \
path.replace(0, (sizeof(prefix)/sizeof(wchar_t)) - 1, buffer); \
if (Exists(path)) return path; \
}
std::wstring Resolve(std::wstring path)
{
using namespace boost::algorithm;
wchar_t buffer[MAX_PATH];
trim(path);
if (path.empty() || Exists(path)) return path;
//Start by trying to see if we have a quoted path
if (path[0] == L'"') {
return std::wstring(path.begin() + 1, std::find(path.begin() + 1, path.end(), L'"'));
}
//Check for those nasty cases where the beginning of the path has no root
PATH_PREFIX_RESOLVE(path, L"\\", L"");
PATH_PREFIX_RESOLVE(path, L"?\?\\", L"");
PATH_PREFIX_RESOLVE(path, L"\\?\\", L"");
PATH_PREFIX_RESOLVE(path, L"globalroot\\", L"");
PATH_PREFIX_RESOLVE(path, L"system32\\", L"%systemroot%\\System32\\");
PATH_PREFIX_RESOLVE(path, L"systemroot\\", L"%systemroot%\\");
static std::vector<std::wstring> pathExts;
if (pathExts.empty()) {
#define MAX_ENVVAR 32767
wchar_t pathext[MAX_ENVVAR];
DWORD length = GetEnvironmentVariableW(L"PATHEXT", pathext, MAX_ENVVAR);
if (!length) WindowsApiException::ThrowFromLastError();
split(pathExts, pathext, std::bind2nd(std::equal_to<wchar_t>(), L';'));
pathExts.insert(pathExts.begin(), std::wstring());
}
std::wstring::iterator currentSpace = path.begin();
do {
currentSpace = std::find(currentSpace, path.end(), L' ');
std::wstring currentPath(path.begin(), currentSpace);
std::wstring::size_type currentPathLength = currentPath.size();
typedef std::vector<std::wstring>::const_iterator ExtIteratorType;
for(ExtIteratorType it = pathExts.begin(); it != pathExts.end(); it++) {
currentPath.replace(currentPathLength, currentPath.size() - currentPathLength, *it);
if (Exists(currentPath)) return currentPath;
}
if (currentSpace != path.end())
currentSpace++;
} while (currentSpace != path.end());
return path;
}
}
It's used about 6 times within the scope of a single function (that's it), but macros seem to have "bad karma" :P
Anyway, the problem here is the sizeof(prefix) part of the macro. If I just replace this with a function taking a const wchar_t[], then the sizeof() will fail to deliver expected results.
Simply adding a size member doesn't really solve the problem either. Making the user supply the size of the constant literal also results in a mess of duplicated constants at the call site.
Any ideas on this one?
| Pass the array by reference, using a template to infer the length. I'll go looking for an example, but basically:
template<size_t N>
bool func(const char (&a)[N], blah, blah) { ... }
EDIT: Someone explained it here:
http://heifner.blogspot.com/2008/04/c-array-size-determination.html
|
2,490,456 | 2,490,499 | How to use unnamed function arguments in C or C++ | How do I use function arguments declared like
void f(double)
{
/**/
}
if it is possible?
| I hope an example can provide some help:
// Declaration, saying there is a function f accepting a double.
void f(double);
// Declaration, saying there is a function g accepting a double.
void g(double);
// ... possibly other code making use of g() ...
// Implementation using the parameter - this is the "normal" way to use it. In
// the function the parameter is used and thus must be given a name to be able
// to reference it. This is still the same function g(double) that was declared
// above. The name of the variable is not part of the function signature.
void g(double d)
{
// This call is possible, thanks to the declaration above, even though
// the function definition is further down.
f(d);
}
// Function having the f(double) signature, which does not make use of
// its parameter. If the parameter had a name, it would give an
// "unused variable" compiler warning.
void f(double)
{
cout << "Not implemented yet.\n";
}
|
2,490,526 | 2,490,607 | Calendar control GUI C++ library | Who knows a good component for a "calendar control" (NOT date/time picker)?
"Calendar control" means something like Mozilla Sunbird:
(source: mozilla.org)
Requirements to the control:
- C++;
- Day/Week/Month view;
- Support of several calendars;
- Without MFC dependences;
Nice to have:
- Open source;
- Cross plathform;
- Free;
- Minimum external dependences (boost etc are fine);
| You are unlikely to find such a control ready made.
Even more unlikely to find one for C++ without MFC dependencies.
Your best bet is to implement it yourself.
|
2,490,573 | 2,490,585 | Strange behaviour with fputs and a loop | When running the following code I get no output but I cannot work out why.
# include <stdio.h>
int main()
{
fputs("hello", stdout);
while (1);
return 0;
}
Without the while loop it works perfectly but as soon as I add it in I get no output. Surely it should output before starting the loop? Is it just on my system? Do I have to flush some sort of buffer or something?
Thanks in advance.
| You have to flush stdout. This happens automatically when you write a newline character. Change the fputs to:
fputs("hello\n", stdout);
Or to:
fputs("hello", stdout);
fflush(stdout);
|
2,490,583 | 2,490,696 | Discrete Curve evolution algorithm | i am trying to implement discrete curve evolution algorithm in c++ do any one help me with psudo code or c code or
some simple steps of your understanding
| I'm not exactly sure what you mean by Discrete Curve evolutionary algorithm, but if you mean a Symbolic regression algorithm, you can start by reading about symbolic regression (or genetic programming in general):
http://en.wikipedia.org/wiki/Symbolic_Regression
There's also some nice existing programs. The Eureqa one has an open API:
http://code.google.com/p/eureqa-api/
|
2,490,776 | 2,490,803 | How do I "unzip" a gzipped stream while reading it | My program is using HTTP to read gzipped files over the network.
I need my program to be able to unzip the content and parse it even when not all the gzipped file arrived yet.
Can it be done ?
If so, can it be done in C++ ? If so, how ?
| You could probably try out the gzstream library:
Gzstream is a small C++ library,
basically just a wrapper, that
provides the functionality of the zlib
C-library in a C++ iostream. It is
freely available under the LGPL
license.
|
2,490,804 | 2,542,440 | How to link Poco library(libraries) to our program in unix environment | I'm having trouble with Poco libraries. I need a simple solution to make the compilation easier. Is there any pkg-config file for Poco library to use it into our make files? Or any alternative solution?
Currently I use Ubuntu GNU/Linux.
I'm trying to use poco libraries in my app, but I don't know how to link Poco libraries to it. In fact I don't know how many libraries should be linked against the app. I want to know if there is an easy way to do it, such as using pkg-config files, as we do with gtkmm, for example:
g++ prog.cc `pkg-config --gtkmm-2.4 --libs --cflags` -o prog
and the pkg-config program appends appropriate libs and header files to our command.
| I don't think Poco comes with any pre-packaged ".pc" files but you should be able to create your own easily and stick them in the lib/pkgconfig directory on your system if you prefer that method.
I don't know exactly where you installed Poco on your system so you may have to do a "find" to locate your files. To compile you need to specify the poco header directory, the poco library directory, and the individual poco libraries. So something like:
g++ -I<path-to-poco-include-dir> -o prog prog.cpp -L<path-to-poco-lib-dir> -l<some-poco-lib> -l<another-poco-lib>
For example:
g++ -I/usr/local/Poco/include -o prog prog.cpp -L/usr/local/Poco/lib -lPocoFoundation -lPocoNet -lPocoNetSSL -lPocoUtil -lPocoXML
There are 20 or so different poco .so files so you obviously need to link the proper ones. Poco makes this pretty easy since the library names conform to the documentation sections - e.g. util stuff is in libPocoUtil.so. If you also compiled debug versions of the libraries they will end in 'd' - e.g. libPocoUtild.so
Again, once you locate all your files you may prefer to create your own poco.pc since you should have the information you need to create it.
|
2,491,164 | 2,491,287 | Calling msi file in c from CreateProcess | Is there any option to call msi file from CreateProcess in c language in window OS.
| The Windows ShellExecute function will open a file of a registered type with the correct application, which I think is what you are asking about.
|
2,491,254 | 2,549,786 | "preprocess current file" addin for Visual Studio? (C++ ) | I realize that Visual Studio has the "/P" option to generate preprocessed files, but it's extremely inconvenient. I'm looking for an addin that allows you to right-click on a file and select "view preprocessed" - or any similar solution that would basically preprocess the currently-open file (with the appropriate options from the current configuration) and show me the output, with no extra hassle. Does such a thing exist?
| There's no really elegant way of doing this using the External Tools menu, but here's a solution that will work:
Create a new configuration for your project. Call it something like "Debug-Preproc". In this configuration, set the /P switch for the compiler. (Preprocess, no compilation.)
Go to the External Tools setup menu. Create a new item called "Preprocess Project". Set the options to:
Command: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe
Arguments: $(ProjectDir)$(ProjectFileName) /Build "Debug-Preproc|Win32"
You can now use the "Preprocess Project" option on your menu to run the preprocessor against all source files in the currently selected project. It will generate [filename].i for each one, which you can open in a text editor.
If you want, you can create an additional step to open the file in a text editor by adding a new external tool to your editor to open $(ItemFileName).i.
It's not nearly as clean or convenient as being able to right-click a file and pick "preprocess", but I think it's the best you'll get short of writing an extension.
|
2,491,379 | 2,491,411 | Function Pointer from base class | i need a Function Pointer from a base class. Here is the code:
class CActionObjectBase
{
...
void AddResultStateErrorMessage( const char* pcMessage , ULONG iResultStateCode);
...
}
CActionObjectCalibration( ): CActionObjectBase()
{
...
m_Calibration = new CCalibration(&CActionObjectBase::AddResultStateErrorMessage);
}
class CCalibration
{
...
CCalibration(void (CActionObjectBase::* AddErrorMessage)(const char*, ULONG ));
...
void (CActionObjectBase::* m_AddErrorMessage)(const char*, ULONG );
}
Inside CCalibration in a Function occurs the Error. I try to call the Function Pointer like this:
if(m_AddErrorMessage)
{
...
m_AddErrorMessage("bla bla", RSC_FILE_ERROR);
}
The Problem is, that I cannot compile. The Error Message says something like:
error C2064: Expression is no Function, that takes two Arguments.
What is wrong?
regards
camelord
| You need to invoke m_AddErrorMessage on an object, something like:
(something->*m_AddErrorMessage)(...)
|
2,491,556 | 2,491,581 | Why does gcc think that I am trying to make a function call in my template function signature? | GCC seem to think that I am trying to make a function call in my template function signature. Can anyone please tell me what is wrong with the following?
227 template<class edgeDecor, class vertexDecor, bool dir>
228 vector<Vertex<edgeDecor,vertexDecor,dir>> Graph<edgeDecor,vertexDecor,dir>::vertices()
229 {
230 return V;
231 };
GCC is giving the following:
graph.h:228: error: a function call cannot appear in a constant-expression
graph.h:228: error: template argument 3 is invalid
graph.h:228: error: template argument 1 is invalid
graph.h:228: error: template argument 2 is invalid
graph.h:229: error: expected unqualified-id before ‘{’ token
Thanks a lot.
| You should put space between two >. >> is parsed as a bit-shift operator, not two closing brackets.
|
2,491,786 | 2,492,000 | copy constructor by address | I have two copy constructors
Foo(Foo &obj){
}
Foo(Foo *obj){
}
When will the second copy constructor will get called?
| Leaving aside that the second constructor isn't a copy constructor - you actually wanted to know when the second constructor will be called.
The Foo(Foo* obj); constructor is a single parameter constructor - because it hasn't been marked with the explicit keyword, it provides an implicit conversion from Foo* to Foo. It may be called at any time where a Foo* is used in the place of a Foo or const Foo& - if it's being called unexpectedly, that's almost certainly what's happening.
In general, single parameter constructors should either be copy constructors (which other answers have explained) or should be marked explicit. Constructors which provide implicit conversions should be used sparingly.
|
2,492,020 | 2,492,341 | how to view contents of STL containers using GDB 7.x | I have been using the macro solution, as it is outlined here. However, there is a mention on how to view them without macros. I am referring to GDB version 7 and above.
Would someone illustrate how?
Thanks
| Get the python viewers from SVN
svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
Add the following to your ~/.gdbinit
python
import sys
sys.path.insert(0, '/path/to/pretty-printers/dir')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end
Then print should just work:
std::map<int, std::string> the_map;
the_map[23] = "hello";
the_map[1024] = "world";
In gdb:
(gdb) print the_map
$1 = std::map with 2 elements = { [23] = "hello", [1024] = "world" }
To get back to the old view use print /r (/r is for raw).
See also: http://sourceware.org/gdb/wiki/STLSupport
|
2,492,318 | 2,492,395 | Is it undefined behavior in the case of the private functions call in the initializer list? | Consider the following code:
struct Calc
{
Calc(const Arg1 & arg1, const Arg2 & arg2, /* */ const ArgN & argn) :
arg1(arg1), arg2(arg2), /* */ argn(argn),
coef1(get_coef1()), coef2(get_coef2())
{
}
int Calc1();
int Calc2();
int Calc3();
private:
const Arg1 & arg1;
const Arg2 & arg2;
// ...
const ArgN & argn;
const int coef1; // I want to use const because
const int coef2; // no modification is needed.
int get_coef1() const {
// calc coef1 using arg1, arg2, ..., argn;
// undefined behavior?
}
int get_coef2() const {
// calc coef2 using arg1, arg2, ..., argn and coef1;
// undefined behavior?
}
};
struct Calc is not completely defined when I call get_coef1 and get_coef2
Is this code valid? Can I get UB?
|
12.6.2.8: Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly,
an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However,
if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer)
before all the mem-initializers for base classes have completed, the result of the operation is undefined.
So you can initialize your class members this way, but not base classes. And, as others pointed, you should be aware of members initialization order, if your function uses some of their values.
|
2,492,676 | 2,492,688 | error in C++, what to do ?: could not find an match for ostream::write(long *, unsigned int) | I am trying to write data stored in a binary file using turbo C++. But it shows me an error
could not find an match for ostream::write(long *, unsigned int)
I want to write a 4 byte long data into that file. When i tries to write data using char pointer. It runs successfully. But i want to store large value i.e. eg. 2454545454
Which can be stored in long only.
I dont know how to convert 1 byte into bit. I have 1 byte of data as a character.
Moreover what i m trying to do is to convert 4 chars into long and store data into it. And at the other side i want to reverse this so as to retrieve how many bytes of data i have written.
long *lmem;
lmem=new long;
*lmem=Tsize;
fo.write(lmem,sizeof(long));// error occurs here
delete lmem;
I am implementing steganography and i have successfully stored txt file into image but trying to retrieve that file data now.
EDIT:
I am using Turbo Complier.
| Cast it to a char*
long *lmem;
lmem=new long;
*lmem=Tsize;
fo.write(reinterpret_cast<char*>(lmem),sizeof(long));
delete lmem;
Or even better (as allocation on the stack is far faster and less error prone)
long lmem = Tsize;
fo.write(reinterpret_cast<char*>(&lmem),sizeof(long));
If Tsize is addressable and a long you could do this:
fo.write(reinterpret_cast<char*>(&Tsize),sizeof(long));
|
2,492,775 | 2,493,977 | get local time with boost | I didn't find this in documentation: how to get local time (better formatted) with boost?
| Use posix_time to construct a time object from the system clock.
For example, this would output the current system time as an ISO-format string:
namespace pt = boost::posix_time;
pt::to_iso_string(pt::second_clock::local_time());
For formatting alternatives, see the “Conversion to String” section of the above-linked reference and the Date Time Input/Output reference. Alternatively, you can build your own output string using the accessor functions. For example, to get a US-style date:
namespace pt = boost::posix_time;
pt::ptime now = pt::second_clock::local_time();
std::stringstream ss;
ss << static_cast<int>(now.date().month()) << "/" << now.date().day()
<< "/" << now.date().year();
std::cout << ss.str() << std::endl;
Note the month is cast to int so it will display as digits. The default output facet will display it as the three-letter month abbreviation (“Mar” for March).
|
2,492,809 | 2,492,954 | #include headers in C/C++ | After reading several questions regarding problems with compilation (particularly C++) and noticing that in many cases the problem is a missing header #include. I couldn't help to wonder in my ignorance and ask myself (and now to you):
Why are missing headers not automatically checked and added or requested to the programmer?
Such feature is available for Java import statements in Netbeans for example.
| Remember the clash in Java between java.util.Date and java.sql.Date? If someone uses Date in their code, you can't tell whether they forgot import java.util.Date or import java.sql.Date.
In both Java and C++, it is not possible to tell with certainty what import/include statement is missing. So neither language tries. Your IDE might make suggestions for undeclared symbols used in your code.
The problem is further complicated in C++, because the standard says that any standard header can include any other standard header(s). It's therefore very easy to use a function or class without directly including the header which defines it, because your compiler happens to include the right header indirectly. The resulting code works in some implementations but not others, according to whether they share that header dependency.
It's not in general possible for a C++ IDE to tell whether a header dependency is "guaranteed", or just an incidental implementation detail that users shouldn't rely on. Obviously for standard libraries it could just know what's defined in what headers, but as soon as you get to third party libraries it gets quite uncertain.
I think most C++ programmers expect to have to look up what headers define what symbols. With Java, the one-public-class-per-file rule simplifies this considerably, and you just import the packages/classes you want. C++ doesn't have packages, and the only way for the IDE to find a class called my_namespace::something::MyClass is to search for it in every header file.
|
2,492,934 | 2,492,952 | C++ Reserve Memory Space | is there any way to reserve memory space to be used later by default Windows Memory Manager so that my application won't run out of memory if my program don't use space more than I have reserved at start of my program?
| There is no point in doing this kind of thing when you have virtual memory.
|
2,492,943 | 2,493,109 | boost::multi_array resize exception? | I'm trying to figure out if the boost::multi_array constructor or resize method can throw a bad_alloc exception (or some other exception indicating the allocation or resize failed). I can't find this information in the documentation anywhere.
Clarification (added from comment):
This is a scientific algorithm that can fall back to a less memory intensive (slower) method if the allocation fails. Basically there are two dynamically allocated 3-dimensional arrays to hold "distances" (correlation) between all pairs of genes in a query and all genes in a cross-validation set for each of a large number of datasets. The slower method recalculates each distance on the fly as it is needed. This is for a C++ version of an existing Java implementation, which implemented both methods and would fall back on an out of memory exception. I don't really expect to run out of memory.
| 1st: (answering the real question): As it uses dynamically allocated memory, yes, it can throw std::bad_alloc (I have never seen boost translation std::bad_alloc exceptions; it would be crazy to do so).
2nd: (comment on your clarification): You do need the information of available physical memory to optimize the performance of your algorithm at run-time. However, you cannot rely on std::bad_alloc to determine how much memory you have available, as modern operating systems use such a thing as overcommit, meaning: they (almost) never return a failed allocation attempt, but instead just give you some "memory", which will only fail to jump into existence when you actually try to access it.
In Java this may work as the VM is doing many things for you: it tries to allocate some continuous memory chunks, and does so with respect to the available physical memory, and the available unused physical memory to decide whether it should stress the GC more or just allocate a larger junk. Also, for performance reason you need to take into account that virtual memory and physical memory are quite different concepts.
If you need to performance-optimize you algorithms for such cases (which may well be necessary, depending on your area of work), you need to inspect your platform-specific functions which can tell you how "the real world" looks like.
|
2,492,966 | 2,492,979 | OpenGL: Disable texture colors? | Is it possible to disable texture colors, and use only white as the color? It would still read the texture, so i cant use glDisable(GL_TEXTURE_2D) because i want to render the alpha channels too.
All i can think of now is to make new texture where all color data is white, remaining alpha as it is.
I need to do this without shaders, so is this even possible?
Edit: to clarify: i want to use both textures: white and normal colors.
Edit: APPARENTLY THIS IS NOT POSSIBLE
| What about changing all texture color (except alpha) to white after they are loaded and before they are utilized in OpenGL? If you have them as bitmaps in memory at some point, it should be easy and you won't need separate texture files.
|
2,493,131 | 2,493,231 | Which type of design pattern should be used to create an emulator? | I have programmed an emulator, but I have some doubts about how to organizate it properly, because, I see that it has some problems about classes connection (CPU <-> Machine Board).
For example: I/O ports, interruptions, communication between two or more CPU, etc.
I need for the emulator to has the best performance and good understanding of the code.
PD: Sorry for my bad English.
EDITED:
Asking for multiple patterns.
| You have two closely-related things going on here.
The emulator is a collection of Command definitions. Each thing the emulator can do is a command. Some commands are nested sequences of commands.
The emulator has a number of internal State definitions. Each thing the emulator does updates one or more state objects.
|
2,493,227 | 2,493,377 | Pitfalls when converting C++/CLI to C++ | I have a library written in C++/CLI and I want to open it up. I want it to be as cross-platform as possible and be able to write bindings to it for other languages to use (Java, Python, etc, etc). To do this, the library needs to be in plain C++ for maximum flexibility. I figure that the logical structures are already there, I just need to replace the .NET libraries it uses with the standard C++ ones. Is this a misguided notion? What should I watch out for when making this transition?
| It might be more trouble than it's worth. Here is what you might come across:
There is no garbage collection in C++. This is the big one. This may require a significant redesign of your library just to convert. If you are using at least C++ tr1, or the boost library, you can sort of get there by using shared_ptr, but there are important fundamental differences. For example, you must be wary of circular dependencies. Also, they make debugging difficult without specific support for them in the debugger.
Functions in .Net classes which have no equivalent in C++ stl or the standard library. Probably the biggest hurtle will be any string manipulation code you have written since there are lot of differences there.
Class libraries/assemblies are not built-in to C++ - every platform has its own method of creating dynamic or shared libraries, and there isn't much support for C++ shared libraries - only C libraries in many cases. Be prepared to make everything a static library.
You must manage all your resources yourself.
|
2,493,229 | 2,493,273 | C++ is there a difference between assignment inside a pass by value and pass by reference function? | Is there a difference between foo and bar:
class A
{
Object __o;
void foo(Object& o)
{
__o = o;
}
void bar(Object o)
{
__o = o;
}
}
As I understand it, foo performs no copy operation on object o when it is called, and one copy operation for assignment. Bar performs one copy operation on object o when it is called and another one for assignment. So I can more or less say that foo uses 2 times less memory than bar (if o is big enough). Is that correct ?
Is it possible that the compiler optimises the bar function to perform only one copy operation on o ? i.e. makes __o pointing on the local copy of argument o instead of creating a new copy?
| It depends. For example, if the compiler decides to inline the function, obviously there will be no copy since there is no function call.
If you want to be sure, pass by const-reference:
void bar(const Object& o)
This makes no copies. Note your non-const version requires an lvalue, because the reference is mutable. foo(Object()) wouldn't work, but temporaries (rvalues) can be bound to a const-reference.
Double-underscores in identifiers are reserved for the compiler, by the way.
|
2,493,257 | 2,501,751 | Is there a way to use Qt's unit testing modules as part of a Code::Blocks project with the QtWorkbench plugin? | We're developing a Qt project using the Code::Blocks IDE with the QtWorkbench plugin. We'd like to take advantage of Qt's unit testing modules to test our code, but from what I've read online, the only way to do so is to use qmake to manually create a new "project" and makefile for each unit test and then to build and execute that project.
Does anyone know of a way to integrate tests with our overall project to have them built and run automatically when the project is built, specifically within the context of Code::Blocks?
| http://www.archivum.info/qt-interest@trolltech.com/2008-09/00297/Re:-Usage-of-QTestLib.html
http://qtcreator.blogspot.com/2009/10/automatically-running-unit-tests.html
|
2,493,297 | 2,493,424 | Appending to QList of QList | I'm trying to append items to a QList at runtime, but I'm running on a error message. Basically what I'm trying to do is to make a QList of QLists and add a few customClass objects to each of the inner lists. Here's my code:
widget.h:
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
public slots:
static QList<QList<customClass> > testlist(){
QList<QList<customClass> > mylist;
for(int w=0 ; w<5 ; w++){
mylist.append(QList<customClass>());
}
for(int z=0 ; z<mylist.size() ; z++){
for(int x=0 ; x<10 ; x++){
customClass co = customClass();
mylist.at(z).append(co);
}
}
return mylist;
}
};
customclass.h:
class customClass
{
public:
customClass(){
this->varInt = 1;
this->varQString = "hello world";
}
int varInt;
QString varQString;
};
main.cpp:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
QList<QList<customClass> > list;
list = w.testlist();
w.show();
return a.exec();
}
But when I try to compile the application, it gives off this error:
error: passing `const QList<customClass>' as `this' argument of `void List<T>::append(const T&) [with T = customClass]' discards qualifiers
I also tried inserting the objects using foreach:
foreach(QList<customClass> list, mylist){
for(int x=0 ; x<10 ; x++){
list.append(customClass());
}
}
The error was gone, but the customClass objects weren't appended, I could verify that by using a debugging loop in main that showed the inner QLists sizes as zero. What am I doing wrong?
| Qt Reference says:
const T & at ( int i ) const
but not:
T& at ( int i )
so there's no non-const version of at. You have to use operator[] instead.
So change it to:
mylist[z].append(co);
and it will work. I even tested it.
I think the foreach version doesn't work, because in foreach(QList<customClass> list, mylist) QList<customClass> list is not reference. But foreach(QList<customClass>& list, mylist) doesn't compile. So you'll have to use the normal for(...) version.
|
2,493,372 | 2,495,250 | How to properly recreate BITMAP, that was previously shared by CreateFileMapping()? | Dear friends, I need your help.
I need to send .bmp file to another process (dialog box) and display it there, using MMF(Memory Mapped File)
But the problem is that image displays in reversed colors and upside down.
Here's source code:
In first application I open picture from HDD and link it to the named MMF "Gigabyte_picture"
HANDLE hFile = CreateFile("123.bmp", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, "Gigabyte_picture");
In second application I open mapped bmp file and at the end I display m_HBitmap on the static component, using SendMessage function.
HANDLE hMappedFile = OpenFileMapping(FILE_MAP_READ, FALSE, "Gigabyte_picture");
PBYTE pbData = (PBYTE) MapViewOfFile(hMappedFile, FILE_MAP_READ, 0, 0, 0);
BITMAPINFO bmpInfo = { 0 };
LONG lBmpSize = 60608; // size of the bmp file in bytes
bmpInfo.bmiHeader.biBitCount = 32;
bmpInfo.bmiHeader.biHeight = 174;
bmpInfo.bmiHeader.biWidth = 87;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biSizeImage = lBmpSize;
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
UINT * pPixels = 0;
HDC hDC = CreateCompatibleDC(NULL);
HBITMAP m_HBitmap = CreateDIBSection(hDC, &bmpInfo, DIB_RGB_COLORS, (void **)& pPixels, NULL, 0);
SetBitmapBits(m_HBitmap, lBmpSize, pbData);
SendMessage(gStaticBox, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP,(LPARAM)m_HBitmap);
/////////////
HWND gStaticBox = CreateWindowEx(0, "STATIC","",
SS_CENTERIMAGE | SS_REALSIZEIMAGE | SS_BITMAP | WS_CHILD | WS_VISIBLE,
10,10,380, 380, myDialog, (HMENU)-1,NULL,NULL);
| pbData points to begin of bitmap data, which points to bitmap header.
Give SetBitmapBits pointer to raw data: pbData + header size + optional pallete.
|
2,493,431 | 2,493,450 | C++, array of objects without <vector> | I want to create in C++ an array of Objects without using STL.
How can I do this?
How could I create array of Object2, which has no argumentless constructor (default constructor)?
| If the type in question has an no arguments constructor, use new[]:
Object2* newArray = new Object2[numberOfObjects];
don't forget to call delete[] when you no longer need the array:
delete[] newArray;
If it doesn't have such a constructor use operator new to allocate memory, then call constructors in-place:
//do for each object
::new( addressOfObject ) Object2( parameters );
Again, don't forget to deallocate the array when you no longer need it.
|
2,493,482 | 2,493,668 | Can I write functors using a private nested struct? | Given this class:
class C
{
private:
struct Foo
{
int key1, key2, value;
};
std::vector<Foo> fooList;
};
The idea here is that fooList can be indexed by either key1 or key2 of the Foo struct. I'm trying to write functors to pass to std::find_if so I can look up items in fooList by each key. But I can't get them to compile because Foo is private within the class (it's not part of C's interface). Is there a way to do this without exposing Foo to the rest of the world?
Here's an example of code that won't compile because Foo is private within my class:
struct MatchKey1 : public std::unary_function<Foo, bool>
{
int key;
MatchKey1(int k) : key(k) {}
bool operator()(const Foo& elem) const
{
return key == elem.key1;
}
};
| I'd do something like this.
Header:
class C
{
private:
struct Foo
{
int index;
Bar bar;
};
// Predicates used to find Notification instances.
struct EqualIndex;
struct EqualBar;
std::vector<Foo> fooList;
};
Source:
// Predicate for finding a Foo instance by index.
struct C::EqualIndex : std::unary_function<C::Foo, bool>
{
EqualIndex(int index) : index(index) { }
bool operator()(const C::Foo& foo) const { return foo.index == index; }
const int index;
};
// Predicate for finding a Foo instance by Bar.
struct C::EqualBar : std::unary_function<C::Foo, bool>
{
EqualBar(const Bar& bar) : bar(bar) { }
bool operator()(const C::Foo& foo) const { return foo.bar == bar; }
const Bar& bar;
};
Usage:
// Find the element containing the Bar instance someBar.
std::vector<Foo>::iterator it = std::find_if(fooList.begin(),
fooList.end(),
EqualBar(someBar));
if (it != fooList.end())
{
// Found it.
}
Sort of...
|
2,493,593 | 2,493,899 | QuantLib starter guide | Is there a good starter document on quantlib (http://quantlib.org)? The examples are not well documented, and the help does not give that much insight.
| Well there are
hundreds of unit tests,
a dozen or more examples
over 1000 pages of Doxygen-generated documentation
several introductory book chapters on the design drafted by Luigi (lead developer)
All this is complicated because the topic is complicated. The No Free Lunch theorem seems to hold for code too ;-)
Thanks for adding the quantlib tag. We should have some more questions here.
|
2,493,600 | 2,493,610 | What is wrong with this C++ Code? | i am a beginner and i have a problem :
this code doesnt compile :
main.cpp:
#include <stdlib.h>
#include "readdir.h"
#include "mysql.h"
#include "readimage.h"
int main(int argc, char** argv) {
if (argc>1){
readdir(argv[1]);
// test();
return (EXIT_SUCCESS);
}
std::cout << "Bitte Pfad angeben !" << std::endl ;
return (EXIT_FAILURE);
}
readimage.cpp
#include <Magick++.h>
#include <iostream>
#include <vector>
using namespace Magick; using namespace std;
void readImage(std::vector<string> &filenames) {
for (unsigned int i = 0; i < filenames.size(); ++i) {
try {
Image img("binary/" + filenames.at(i));
for (unsigned int y = 1; y < img.rows(); y++) {
for (unsigned int x = 1; x < img.columns(); x++) {
ColorRGB rgb(img.pixelColor(x, y));
// cout << "x: " << x << " y: " << y << " : " << rgb.red() << endl;
}
}
cout << "done " << i << endl;
} catch (Magick::Exception & error) {
cerr << "Caught Magick++ exception: " << error.what() << endl;
}
} }
readimage.h
#ifndef _READIMAGE_H
#define _READIMAGE_H
#include <Magick++.h>
#include <iostream>
#include <vector>
#include <string>
using namespace Magick;
using namespace std;
void readImage(vector<string> &filenames)
#endif /* _READIMAGE_H */
If want to compile it with this code :
g++ main.cpp Magick++-config --cflags
--cppflags --ldflags --libs readimage.cpp
i get this error message :
main.cpp:5: error: expected
initializer before ‘int’
i have no clue , why ? :(
Can somebody help me ? :)
| In readimage.h, you are missing a semicolon after your readImage function declaration.
|
2,493,687 | 2,520,519 | Development environment to use/learn VTK with C++ | I am a newbie with VTK and C++ (but am well versed in the concepts/Java etc). I will eventually need to use both QT and VTK for my project. I would like to know if there is a development environment or editor for VTK (using C++) similar to VTK Designer? With VTK Designer I am very disappointed that there is no feature to convert the VTK output into C++ code.
| I've been working with VTK/Qt for a while, and I doubt there is something like VTK Designer that will convert a pipeline to C++ code.
Everything will need to be hand coded in - and its fairly simple. If you are not sure about the exact C++ implementation of your pipeline, I recommend looking at the VTK samples / tests at http://www.vtk.org/doc/nightly/html/classes.html
For example, if you would like to implement the vtkStreamLine filter for streamlines, go to the Doxygen page for the class ( http://www.vtk.org/doc/nightly/html/classvtkStreamLine.html ) and click on the "Tests" link to look at existing implementations of the class that has examples of how to setup the pipeline.
|
2,493,785 | 2,493,808 | How I can print the wchar_t values to console? | Example:
#include <iostream>
using namespace std;
int main()
{
wchar_t en[] = L"Hello";
wchar_t ru[] = L"Привет"; //Russian language
cout << ru
<< endl
<< en;
return 0;
}
This code only prints HEX-values like adress.
How to print the wchar_t string?
| Edit: This doesn’t work if you are trying to write text that cannot be represented in your default locale. :-(
Use std::wcout instead of std::cout.
wcout << ru << endl << en;
|
2,494,044 | 2,494,182 | Sorting a string array in C++ no matter of 'A' or 'a' and with å, ä ö? | How do you sort an array of strings in C++ that will make this happen in this order:
mr Anka
Mr broWn
mr Ceaser
mR donK
mr ålish
Mr Ätt
mr önD
//following not the way to get that order regardeless upper or lowercase and å, ä, ö
//in forloop...
string handle;
point1 = array1[j].find_first_of(' ');
string forename1(array1[j].substr(0, (point1)));
string aftername1(array1[j].substr(point1 + 1));
point2 = array1[j+1].find_first_of(' ');
string forename2(array1[j+1].substr(0, (point2)));
string aftername2(array1[j+1].substr(point2 + 1));
if(aftername1 > aftername2){
handle = array1[j];
array1[j] = array1[j+1];
array1[j+1] = handle;//swapping
}
if(aftername1 == aftername2){
if(forname1 > forname2){
handle = array1[j];
array1[j] = array1[j+1];
array1[j+1] = handle;
}
}
| Tables and transformations.
I would first convert the string to either all uppercase or all lowercase:
#include <cctype>
#include <algorithm>
#include <string>
std::string test_string("mR BroWn");
std::transform(test_string.begin(), test_string.end(),
test_string.begin(),
std::tolower);
Next I would check for exceptions or use an equivalency table. If the character in question is in an array of exception characters, then use an equivalency table.
|
2,494,062 | 2,494,470 | Managed .NET Equivalent to CreateFile & WriteFile from WinBase (kernel32.dll) | I am working with a legacy file format.
The file is created using unmanaged C++ that utilizes the WinBase.h CreateFile() & WriteFile() functions (found in the kernel32.dll).
I have been using P/Invoke interop to access these native functions like so:
[DllImport("kernel32.dll")]
public static extern bool WriteFile(
IntPtr hFile,
byte[] lpBuffer,
uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
[In] ref NativeOverlapped lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteFileEx(
IntPtr hFile,
byte[] lpBuffer,
uint nNumberOfBytesToWrite,
[In] ref NativeOverlapped lpOverlapped,
WriteFileCompletionDelegate lpCompletionRoutine);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
public delegate void WriteFileCompletionDelegate(
UInt32 dwErrorCode,
UInt32 dwNumberOfBytesTransfered,
ref NativeOverlapped lpOverlapped);
The issue with this is when I call WriteFile(), the file is always overwritten by the proceeding call.
Preferable I would like to use a compatible .NET equivalent that would allow me to produce the exact same format of output.
The C++ code looks like so: (WORKING)
HANDLE hFile = CreateFile(sFileName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hFile, &someVar1, sizeof(bool), &dwWritten, NULL);
WriteFile(hFile, &someVar1, sizeof(long), &dwWritten, NULL);
WriteFile(hFile, &someVar2, sizeof(bool), &dwWritten, NULL);
WriteFile(hFile, sStr.GetBuffer(0), dwStrLen*sizeof(TCHAR), &dwWritten, NULL);
CloseHandle(hFile);
The C# is as follows: (OVERWRITES PREVIOUS WRITE i.e. will output file will contain only 'T')
{
var hFile = COMFileOps2.CreateFile(FILE_NAME, (uint) COMFileOps2.FILE_GENERIC_WRITE,
COMFileOps2.FILE_SHARE_WRITE, IntPtr.Zero, COMFileOps2.CREATE_ALWAYS,
COMFileOps2.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
var natOverlap = new NativeOverlapped();
COMFileOps2.WriteFileEx(hFile, new byte[] {(byte) 't'}, 1, ref natOverlap, Callback);
COMFileOps2.WriteFileEx(hFile, new byte[] { (byte)'e' }, 1, ref natOverlap, Callback);
COMFileOps2.WriteFileEx(hFile, new byte[] { (byte)'s' }, 1, ref natOverlap, Callback);
COMFileOps2.WriteFileEx(hFile, new byte[] { (byte)'T' }, 1, ref natOverlap, Callback);
COMFileOps2.CloseHandle(hFile);
}
private static void Callback(uint dwerrorcode, uint dwnumberofbytestransfered, ref NativeOverlapped lpoverlapped)
{
throw new NotImplementedException();
}
UPDATE: The following C# code will write out "Test":
uint written;
uint position = 0;
var natOverlap0 = new NativeOverlapped();
COMFileOps.WriteFile(hFile, new byte[] {(byte) 'T'}, 1, out written, ref natOverlap0);
position += written;
var natOverlap1 = new NativeOverlapped {OffsetLow = (int) position};
COMFileOps.WriteFile(hFile, new byte[] { (byte)'e' }, 1, out written, ref natOverlap1);
position += written;
var natOverlap2 = new NativeOverlapped { OffsetLow = (int)position };
COMFileOps.WriteFile(hFile, new byte[] { (byte)'s' }, 1, out written, ref natOverlap2);
position += written;
var natOverlap3 = new NativeOverlapped { OffsetLow = (int)position };
COMFileOps.WriteFile(hFile, new byte[] { (byte)'t' }, 1, out written, ref natOverlap3);
COMFileOps.CloseHandle(hFile);
Thanks.
| WriteFileEx only runs asynchronously, you must provide a SEPARATE instance of OVERLAPPED for each pending call, and you must setup the OVERLAPPED members, such as the file offset. Then you can't call CloseHandle until all the operations finish. And using a local variable for OVERLAPPED and letting it go out of scope? Your data getting overwritten is the least of the things that can go wrong with the code you show.
So that's why your code doesn't work. I don't know why you switched from WriteFile to WriteFileEx in the first place. In addition, calling the Win32 API from C# is quite inconvenient, although occasionally necessary. But first see if the .NET File APIs do what you need.
Since .NET File APIs tend to work with either strings (in textmode, watch for newline conversions and such) or arrays of bytes, you need to turn your other variables into byte[]. The BitConverter class is your friend here.
|
2,494,391 | 2,494,591 | Is there a size limit on WritePrivateProfileStruct? | I'm trying to write an INI file using the WritePrivateProfileString and WritePrivateProfileStruct functions.
I found that when the byte count is relatively low, WritePrivateProfileStruct and GetPrivateProfileStruct work fine, but with a higher byte count (62554 bytes in my case), the Write function seems to work but the Get function doesn't.
I haven't found any size limit for these functions on the MS documentation. Why is this happening?
| Yes, I repro. The largest buffer I can read back is 32766 bytes. Larger values produce ERROR_BAD_LENGTH. With the checksum and the terminating zero, looks to me that it uses an internal buffer that is (32766+2) * 2 = 65536 bytes long. Makes somewhat sense, this is a legacy 16-bit API.
You really ought to consider using a regular file. But a workaround is to split the buffer in two.
|
2,494,471 | 2,494,478 | C++, is it possible to call a constructor directly, without new? | Can I call constructor explicitly, without using new, if I already have a memory for object?
class Object1{
char *str;
public:
Object1(char*str1){
str=strdup(str1);
puts("ctor");
puts(str);
}
~Object1(){
puts("dtor");
puts(str);
free(str);
}
};
Object1 ooo[2] = {
Object1("I'm the first object"), Object1("I'm the 2nd")
};
do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory
| Sort of. You can use placement new to run the constructor using already-allocated memory:
#include <new>
Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")};
do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
new (&ooo[0]) Object1("I'm the 3rd object in place of first");
So, you're still using the new keyword, but no memory allocation takes place.
|
2,494,610 | 2,494,621 | C++ function call routes resolver | I'm looking for a tool that will tell/resolve for every function all the call paths (call it "routes") to it.
For example:
void deeper(int *pNumber)
{
*pNumber++;
}
void gateA(int *pNumber)
{
deeper(pNumber);
}
void gateB(int *pNumber)
{
gateA(pNumber);
}
void main()
{
int x = 123;
gateA(&x);
gateB(&x);
}
See?
I need a tool that will tell me all the routes to deeper(), and more if possible.
By saying "more" I mean that it will tell me if the pointer is the same as been provided to the calling function.
This will greatly save me time.
Thanks!
| Doxygen will do that for you. It'll draw you nice inheritance trees and show you everyone who is calling (and called by) your functions.
|
2,494,862 | 2,494,998 | Reading a stream in C++ | I have the following code:
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"?
| You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.
Since you appear to be using Windows, you would use GetLastError to get the raw code and FormatMessage to convert it to a textual description.
|
2,495,000 | 2,579,699 | Optimal Eclipse CDT (C++) experience in March of 2010 | I am a student who will be using C++ next quarter. I really enjoyed using the Galileo release of Eclipse with Java and I would like to continue using Eclipse for for C++ development.
I am now experimenting with C++ development on Eclipse. I am running Eclipse 3.5 SR2 with CDT 6.02. My operating system is Windows 7 and I have installed MinGW-5.1.6. Version 6.3 of GDB is installed.
I have it compiling and stepping through code. However, I have the suspicion that I'm just crawling along and have yet to "shift the car out of first gear". I've spent about a week poking around on the Web to learn what constitutes and "optimal" C++ Eclipse experience. In particular, I'm interested in round-tripping with UML and unit testing.
My exploration of the Web became an archeological dig. I turned up how-to articles from 2003, alternative MinGW distros, references to plugins, dead-links, more references to plugins, passionate discussions on gdb bugs, and more references to plugins.
I no longer have any idea what might constitute an optimal C++ Eclipse environment. Would members of the community like to weigh-in on what they consider to be the current optimal experience for C++ development using Eclipse?
| Here is what I ended up with for a C++ development environment on Windows 7.
Compiler & libraries
Nuwen MinGW Distro.
It includes the Boost libraries which are necessary for the unit testing framework.
A big thanks to Stephan T. Lavavej for making this distribution available.
Debugger
The GNU debugger as built for Windows.
I copied the file gdb.exe into my C:\MinGW\bin folder and it worked well.
Thanks for Equation Solution for providing win32 and win64 binaries of the GDB executable.
IDE
Eclipse IDE for C/C++ Developers.
Unit testing framework
CUTE (C++ Automated Unit Testing Easier).
Download the Eclipse plug-in using Eclipse’s software installation . Add this URL to “Available Software Sites”: http://ifs.hsr.ch/cute/updatesite.
The CUTE Website has excellent installation and usage instructions.
I failed to find a round-trip modeling tool that was useful to me. Exploring free UML tools was like wandering through a city that had been bombed. Dozens of projects stood in various states of usability. Some projects were clearly active, some were clearly abandoned, but most were somewhere in between. Visio continues to be my pragmatic choice for creating UML models.
|
2,495,102 | 2,495,385 | Qt C++ XML, validating against a DTD? | Is there a way to validate an XML file against a DTD with Qt's XML handling? I've tried googling around but can't seem to get a straight answer. If Qt doesn't include support for validating an XML file, what might be the process of implementing validation myself? Any good reference to start with in regards to validating XML against a spec? Thanks for the help!
| You can validate your XML with this : http://qt.nokia.com/doc/4.6/qxmlschema.html
You can also find an example here : XML Schema Validation Example
Hope it helps a bit !
|
2,495,188 | 2,495,231 | How to add canvas in MFC Dialog? | I want to create an application which main window has canvas (or something where I can draw custom things) and some controls, like buttons and edit fields. But I got stuck about how to do it.
I tried to create MFC with SDI, but how to add control to CDC..?
I tried to create one dialog with buttons and edit fields, but which control refers to something I can draw at..?
Please, enlighten me how to do this..
| Its been a few years for me, but here goes:
I don't think that MFC has a specific canvas control. Instead, when I wanted a drawing surface, I added a group box to the form in design mode. I made the group box invisible, so it would not show up at runtime.
In the OnCreate handler for the form view, I created a CWnd, and gave it the size and location of the invisible group box.
I set up an OnPaint message handler for the CWnd, and voila, instant graphics canvas, or a canvas for whatever else you may need.
Now, this was last done five years ago, and MFC may have advanced incrementally since then, but this is the general mechanism.
|
2,495,198 | 2,586,872 | Unable to run OpenMPI across more than two machines | When attempting to run the first example in the boost::mpi tutorial, I was unable to run across more than two machines. Specifically, this seemed to run fine:
mpirun -hostfile hostnames -np 4 boost1
with each hostname in hostnames as <node_name> slots=2 max_slots=2. But, when I increase the number of processes to 5, it just hangs. I have decreased the number of slots/max_slots to 1 with the same result when I exceed 2 machines. On the nodes, this shows up in the job list:
<user> Ss orted --daemonize -mca ess env -mca orte_ess_jobid 388497408 \
-mca orte_ess_vpid 2 -mca orte_ess_num_procs 3 -hnp-uri \
388497408.0;tcp://<node_ip>:48823
Additionally, when I kill it, I get this message:
node2- daemon did not report back when launched
node3- daemon did not report back when launched
The cluster is set up with the mpi and boost libs accessible on an NFS mounted drive. Am I running into a deadlock with NFS? Or, is something else going on?
Update: To be clear, the boost program I am running is
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <iostream>
namespace mpi = boost::mpi;
int main(int argc, char* argv[])
{
mpi::environment env(argc, argv);
mpi::communicator world;
std::cout << "I am process " << world.rank() << " of " << world.size()
<< "." << std::endl;
return 0;
}
From @Dirk Eddelbuettel's recommendations, I compiled and ran the mpi example hello_c.c, as follows
#include <stdio.h>
#include "mpi.h"
int main(int argc, char* argv[])
{
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
printf("Hello, world, I am %d of %d\n", rank, size);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}
It runs fine on a single machine with multiple processes, this includes sshing into any of the nodes and running. Each compute node is identical with the working and mpi/boost directories mounted from a remote machine via NFS. When running the boost program from the fileserver (identical to a node except boost/mpi are local), I am able to run on two remote nodes. For "hello world", however, running the command mpirun -H node1,node2 -np 12 ./hello I get
[<node name>][[2771,1],<process #>] \
[btl_tcp_endpoint.c:638:mca_btl_tcp_endpoint_complete_connect] \
connect() to <node-ip> failed: No route to host (113)
while the all of the "Hello World's" are printed and it hangs at the end. However, the behavior when running from a compute node on a remote node differs.
Both "Hello world" and the boost code just hang with mpirun -H node1 -np 12 ./hello when run from node2 and vice versa. (Hang in the same sense as above: orted is running on remote machine, but not communicating back.)
The fact that the behavior differs from running on the fileserver where the mpi libs are local versus on a compute node suggests that I may be running into an NFS deadlock. Is this a reasonable conclusion? Assuming that this is the case, how do I configure mpi to allow me to link it statically? Additionally, I don't know what to make of the error I get when running from the fileserver, any thoughts?
| The answer turned out to be simple: open mpi authenticated via ssh and then opened up tcp/ip sockets between the nodes. The firewalls on the compute nodes were set up to only accept ssh connections from each other, not arbitrary connections. So, after updating iptables, hello world runs like a champ across all of the nodes.
Edit: It should be pointed out that the fileserver's firewall allowed arbitrary connections, so that was why an mpi program run on it would behave differently than just running on the compute nodes.
|
2,495,254 | 2,499,817 | Qt send signal to main application window | I need a QDialog to send a signal to redraw the main window.
But connect needs an object to connect to.
So I must create each dialog with new and explicitly put a connect() every time.
What I really need is a way of just sending MainWindow::Redraw() from inside any function and having a single connect() inside Mainwindow to receive them.
But you can't make a signal static and dialogs obviously don't inherit from MainWindow.
edit:
Thanks - I don't want to bypass signal/slots. I want to bypass having a main app pointer singleton, like afxGetApp(). But I don't understand how to just send out a signal and have it funnel up (or down?) to mainwindow where I catch it. I was picturing signals/slots as like exceptions
| Let clients post CustomRedrawEvents to the QCoreApplication.
class CustomRedrawEvent : public QEvent
{
public:
static Type registeredEventType() {
static Type myType
= static_cast<QEvent::Type>(QEvent::registerEventType());
return myType;
}
CustomRedrawEvent() : QEvent(registeredEventType()) {
}
};
void redrawEvent() {
QCoreApplication::postEvent(
QCoreApplication::instance(),
new CustomRedrawEvent());
}
Install an event on the CoreApplication instance and connect to the redraw signal:
class CustomRedrawEventFilter : public QObject
{
Q_OBJECT
public:
CustomRedrawEventFilter(QObject *const parent) : QObject(parent) {
}
signals:
void redraw();
protected:
bool eventFilter(QObject *obj, QEvent *event) {
if( event && (event->type()==CustomRedrawEvent::registeredEventType())) {
emit redraw();
return true;
}
return QObject::eventFilter(obj, event);
}
};
//main()
QMainWindow mainWindow;
QCoreApplication *const coreApp = QCoreApplication::instance();
CustomRedrawEventFilter *const eventFilter(new CustomRedrawEventFilter(coreApp));
coreApp->installEventFilter(eventFilter);
mainWindow.connect(eventFilter, SIGNAL(redraw()), SLOT(update()));
|
2,495,262 | 2,495,408 | Unreachable breakpoint at execut(able/ing) code | I've got two DLLs, one in written in native C++ and the other in C++/CLI. The former is injected into a process, and at a later point in time, loads the latter. While debugging, I noticed that the native DLL's breakpoints were functioning correctly while the other's weren't, even though its code was being executed.
The breakpoints showed this message: This breakpoint will not be hit. No executable code associated with this line. Possible causes include: preprocessor directives or compiler/linker optimizations.
The modules window tells me that the plugin's symbols are loaded. I'm running with its DEBUG build. Any ideas on why this is so and perhaps a fix ?
| The reason for what you faced is that the PDBs ("PDB stands for Program Database, a proprietary file format (developed by Microsoft) for storing debugging information about a program) are not up-to-date.
Try to clean the solution (that contains the managed code DLL) and rebuild it again.
Tip: if you are referring to the DLL, try to put the up-to-date pdbs beside the it. You can get the pdbs from your bin folder.
|
2,495,266 | 2,495,416 | Switching to Java from C++: What are the key points? | I'm an experienced developer, but most of my OO programming experience has been with C++ (and a little Delphi). I'm considering doing some Android work, hence Java.
Coming from the C++ background, what areas of Java are most likely to surprise/annoy/delight me?
I felt sure this would already have been asked, but my searches haven't turned up a similar question.
CW, of course.
| surprise:
Almost everything is on the heap
It can be as fast as C++, even faster in a few cases
The autoboxing of primitives will occasionally cause headaches
annoy:
no unsigned integer types
no preprocessor directives of any kind
no operator overloading
generics are castrated templates
delight:
blessedly quick compilation
No memory management
No segfaults
Most error conditions result in a stack trace that often pinpoints the problem
Enums are really powerful
A standardized, Unicode-aware String class
|
2,495,316 | 2,495,334 | Choice for Socket Server Application: C/C++ or C# | What would be the most sensible choice for building a socket server application, assuming that you had the luxury of choosing between C/C++ or Csharp, and you intend to run multiple instances of the same server on both Windows and Linux servers?
| If you can get the service to run on .NET in Windows and Linux (via Mono), C# is probably the "easier" environment to work with in terms of development.
The C++ route may be a little trickier - you'll have to compile the code for both Linux and Windows, which can get tricky if you're doing low-level/platform-dependent things in C++.
The C++ route may also perform a little better if the code is written well. If you have high load or performance requirements, C++ (or plain C) might be the better route.
|
2,495,348 | 2,495,754 | how can exec change the behavior of exec'ed program | I am trying to track down a very odd crash. What is so odd about it is a workaround that someone discovered and which I cannot explain.
The workaround is this small program which I'll refer to as 'runner':
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
if (argc == 1)
{
fprintf(stderr, "Usage: %s prog [args ...]\n", argv[0]);
return 1;
}
execvp(argv[1], argv + 1);
fprintf(stderr, "execv failed: %s\n", strerror(errno));
// If exec returns because the program is not found or we
// don't have the appropriate permission
return 255;
}
As you can see, all this program does is use execvp to replace itself with a different program.
The program crashes when it is directly invoked from the command line:
/path/to/prog args # this crashes
but works fine when it is indirectly invoked via my runner shim:
/path/to/runner /path/to/prog args # works successfully
For the life of me, I can figure out how having an extra exec can change the behavior of the program being run (as you can see the program does not change the environment).
Some background on the crash. The crash itself is happening in the C++ runtime. Specifically, when the program does a throw, the crashing version incorrectly thinks there is no matching catch (although there is) and calls terminate. When I invoke the program via runner, the exception is properly caught.
My question is any idea why the extra exec changes the behavior of the exec'ed program?
| It's possible that the .so files loaded by the runner are causing the runee to work correctly. Try ldd'ing each of the binaries and see if any libraries are loading different versions/locations.
|
2,495,420 | 2,496,831 | Is there any LAME C++ wrapper\simplifier (working on Linux Mac and Win from pure code)? | I want to create simple pcm to mp3 C++ project. I want it to use LAME. I love LAME but it's really big. so I need some kind of OpenSource working from pure code with pure lame code workflow simplifier. So to say I give it File with PCM and DEST file. Call something like:
LameSimple.ToMP3(file with PCM, File with MP3 , 44100, 16, MP3, VBR);
ore such thing in 4 - 5 lines (examples of course should exist) and I have vhat I needed It should be light, simple, powerfool, opensource, crossplatform.
Is there any thing like this?
| Lame really isn't difficult to use, although there are a lot of optional configuration functions if you need them. It takes slightly more than 4-5 lines to encode a file, but not much more. Here is a working example I knocked together (just the basic functionality, no error checking):
#include <stdio.h>
#include <lame/lame.h>
int main(void)
{
int read, write;
FILE *pcm = fopen("file.pcm", "rb");
FILE *mp3 = fopen("file.mp3", "wb");
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, 44100);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
return 0;
}
|
2,495,460 | 2,522,873 | How to change a QMenu text from english to russian by clicking a button | Please consider we have a menu which has text set "MyMenu" and I want to change the menu text by clicking a button in the same widget from "MyMenu" to "МойМеню". Could you bring a code snippet please for that operation?
| int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));//this is the solution
.............
}
And in the code you can dynamically change the strings if you set them from the begining by using tr() function [tr("your text")].
|
2,495,485 | 2,495,578 | Using new (this) to reuse constructors | This came up recently in a class for which I am a teaching assistant. We were teaching the students how to do copy constructors in c++, and the students who were originally taught java asked if you can call one constructor from another. I know the answer to this is no, as they are using the pedantic flag for their code in class, and the old standards do not have support for this. I found on Stackoverflow and other sites a suggestion to fake this using new (this) such as follows
class MyClass
{
private:
int * storedValue;
public:
MyClass(int initialValue = 0)
{
storedValue = new int(initialValue);
}
~ MyClass()
{
delete storedValue;
}
MyClass(const MyClass &b)
{
new (this) MyClass(*(b.storedValue));
}
int value() {
return *storedValue;
}
};
This is really simple code, and obviously does not save any code by reusing the constructor, but it is just for example.
My question is if this is even standard compliant, and if there are any edge cases that should be considered that would prevent this from being sound code?
Edit: I should note that this seems very dangerous to me, but that is more from a view point of I don't really understand it more than knowing how it can go bad. I just wanted to make sure that if asked about it by students that I can direct them towards why the can or shouldn't do it. I already suggested to them for all practical purposes to use a shared initialization method. This is more of a teaching question than for a practical project.
| C++0x will introduce syntax to allow constructors to call other constructors.
Until then, new(this) works in some cases, but not all. In particular, once in the constructor, your base class(es) are already fully constructed. Reconstructing via new(this) re-calls the base constructors without calling the base destructors, so expect problems if the base classes weren't expecting this kind of hackery - and they probably weren't.
An example for clarity:
class Base
{
public:
char *ptr;
MyFile file;
std::vector vect;
Base()
{
ptr = new char[1000];
file.open("some_file");
}
~Base()
{
delete [] ptr;
file.close();
}
};
class Derived : Base
{
Derived(Foo foo)
{
}
Derived(Bar bar)
{
printf(ptr...); // ptr in base is already valid
new (this) Derived(bar.foo); // ptr re-allocated, original not deleted
//Base.file opened twice, not closed
// vect is who-knows-what
// etc
}
}
or as they say 'hilarity ensues'
|
2,495,503 | 2,496,328 | Using Fortran to call C++ Functions | I'm trying to get some FORTRAN code to call a couple c++ functions that I wrote (c_tabs_ being one of them). Linking and everything works just fine, as long as I'm calling functions that don't belong to a class.
My problem is that the functions I want the FORTRAN code to call belong to a class. I looked at the symbol table using nm and the function name is something ugly like this:
00000000 T _ZN9Interface7c_tabs_Ev
FORTRAN won't allow me to call a function by that name, because of the underscore at the beginning, so I'm at a loss.
The symbol for c_tabs when it's not in a class is quite simple, and FORTRAN has no problems with it:
00000030 T c_tabs_
Any suggestions? Thanks in advance.
| If you make the C++ routine have a C-style interface (as described already), then you can use the ISO C Binding feature of Fortran 2003 to call it. With the ISO C Binding, you can specify the name of the routine and (within limits) the C-types and calling conventions (reference, by value) of the arguments and function return. This method works well and has the advantage of being a standard, and therefore compiler and platform dependent, unlike the old methods of calling C from Fortran. The ISO C Binding is supported by many Fortran 95 compilers, such as gfortran >= 4.3.
|
2,496,338 | 2,496,366 | Are C files renamed to C++ are going to be compilable with C++ compilers after renaming? | C files renamed to C++ are going to be compilable with C++ compilers after renaming?
So I have 25 C files and 1 C++ file I do not want to create Make files or anething like that. I want to turn all that C files into C++ so will simple renaming work or what shall I do?
| In general, yes. You will have to worry about variables named class and such, the sizeof a character literal, and name mangling, and some other rarely encountered issues. If you're converting C99 to C++, you'll have to drop some C99 features.
With regards to name mangling, reference any C symbols by using extern "C". A common idiom is:
#ifdef __cplusplus
extern "C" {
#endif
extern int myGlobal;
extern int myFunction(void);
/* etc */
#ifdef __cplusplus
}
#endif
|
2,496,471 | 2,496,647 | Extracting pair member in lambda expressions and template typedef idiom | I have some complex types here so I decided to use nifty trick to have typedef on templated types. Then I have a class some_container that has a container as a member. Container is a vector of pairs composed of element and vector. I want to write std::find_if algorithm with lambda expression to find element that have certain value. To get the value I have to call first on pair and then get value from element. Below my std::find_if there is normal loop that does the trick. My lambda fails to compile. How to access value inside element which is inside pair?
I use g++ 4.4+ and VS 2010 and I want to stick to boost lambda for now.
#include <vector>
#include <algorithm>
#include <boost\lambda\lambda.hpp>
#include <boost\lambda\bind.hpp>
template<typename T>
class element
{
public:
T value;
};
template<typename T>
class element_vector_pair // idiom to have templated typedef
{
public:
typedef std::pair<element<T>, std::vector<T> > type;
};
template<typename T>
class vector_containter // idiom to have templated typedef
{
public:
typedef std::vector<typename element_vector_pair<T>::type > type;
};
template<typename T>
bool operator==(const typename element_vector_pair<T>::type & lhs, const typename element_vector_pair<T>::type & rhs)
{
return lhs.first.value == rhs.first.value;
}
template<typename T>
class some_container
{
public:
element<T> get_element(const T& value) const
{
std::find_if(container.begin(), container.end(), bind(&typename vector_containter<T>::type::value_type::first::value, boost::lambda::_1) == value);
/*for(size_t i = 0; i < container.size(); ++i)
{
if(container.at(i).first.value == value)
{
return container.at(i);
}
}*/
return element<T>(); //whatever
}
protected:
typename vector_containter<T>::type container;
};
int main()
{
some_container<int> s;
s.get_element(5);
return 0;
}
| Two issues.
The thing that you are going after (element<T>::value) is not a typename.
However, firstly you'll need nested binds: one to access _1.first and another one to access the value of the previous.
Without the typedefs:
std::find_if(
container.begin(), container.end(),
bind(
&element<T>::value,
bind(&std::pair<element<T>, std::vector<T> >::first, boost::lambda::_1)
) == value
);
And so, with your idiom, without the unnecessary typename:
std::find_if( container.begin(), container.end(),
bind(
&vector_containter<T>::type::value_type::first_type::value,
bind(
&vector_containter<T>::type::value_type::first, boost::lambda::_1)
) == value
);
This doesn't seem particularly readable, though. Perhaps a) wait for C++0x lambda, b) write a specific functor for the find_if call, c) just do a manual loop.
|
2,496,631 | 2,534,987 | Can you get access to the NumberFormatter used by ICU MessageFormat | This may be a niche question but I'm working with ICU to format currency strings. I've bumped into a situation that I don't quite understand.
When using the MesssageFormat class, is it possible to get access to the NumberFormat object it uses to format currency strings. When you create a NumberFormat instance yourself, you can specify attributes like precision and rounding used when creating currency strings.
I have an issue where for the South Korean locale ("ko_KR"), the MessageFormat class seems to create currency strings w/ rounding (100.50 -> ₩100).
In areas where I use NumberFormat directly, I set setMaximumFractionDigits and setMinimumFractionDigits to 2 but I can't seem to set this in the MessageFormat.
Any ideas?
| I've determined that gaining access to the internal formatter used is not possible. I've opened a ticket with the ICU project. http://bugs.icu-project.org/trac/ticket/7571#preview
|
2,496,689 | 2,496,728 | not so obvious pointers | I have a class :
class X{
public :
void f ( int ) ;
int a ;
} ;
And the task is "Inside the code provide declarations for :
pointer to int variable of class X
pointer to function void(int) defined inside class X
pointer to double variable of class X"
Ok so pointer to int a will be just int *x = &a, right ? If there is no double in X can I already create pointer to double inside this class ? And the biggest problem is the second task. How one declares pointer to function ?
| These are called pointers to members. They are not regular pointers, i.e. not addresses, but "sort-of" offsets into an instance of the class (it gets a bit tricky with virtual functions.) So:
int X::*ptr_to_int_member;
void (X::*ptr_to_member_func)( int );
double X::*ptr_to_double_member;
|
2,496,742 | 2,496,757 | Why won't C++ allow this default value? | Why won't GCC allow a default parameter here?
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const
{
This is the output I get:
graph.h:82: error: default argument given for parameter 2 of ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool)’
graph.h:36: error: after previous specification in ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool)’
Can anyone see why I'm getting this?
| You seem to already have declared the function (including the default parameter) in graph.h, line 36. Don't repeat the default value in the function implementation, specifying it one time in the declaration is enough.
|
2,496,902 | 2,496,909 | An interesting case of delete and destructor (C++) | I have a piece of code where I can call the destructor multiple times and access member functions even the destructor was called with member variables' values preserved. I was still able to access member functions after I called delete but the member variables were nullified (all to 0). And I can't double delete. Please kindly explain this.
#include <iostream>
using namespace std;
template <typename T>
void destroy(T* ptr)
{
ptr->~T();
}
class Testing
{
public:
Testing() : test(20)
{
}
~Testing()
{
printf("Testing is being killed!\n");
}
int getTest() const
{
return test;
}
private:
int test;
};
int main()
{
Testing *t = new Testing();
cout << "t->getTest() = " << t->getTest() << endl;
destroy(t);
cout << "t->getTest() = " << t->getTest() << endl;
t->~Testing();
cout << "t->getTest() = " << t->getTest() << endl;
delete t;
cout << "t->getTest() = " << t->getTest() << endl;
destroy(t);
cout << "t->getTest() = " << t->getTest() << endl;
t->~Testing();
cout << "t->getTest() = " << t->getTest() << endl;
//delete t; // <======== Don't do it! Double free/delete!
cout << "t->getTest() = " << t->getTest() << endl;
return 0;
}
| This is an exhibit of undefined behavior. Call a member function through a pointer that's been deleted and anything goes - the compiler and runtime aren't required to check for this error, but you certainly can't count on this working.
This falls into a similar category as using memory that's been freed - you might find your old data there (or you might not). You might cause the program to crash (or not). You might even be able to change the data without anything complaining.
But in any case, it's a programming error.
|
2,496,950 | 2,496,978 | setting library include paths in c++ | I just installed gd2 using mac ports (sudo install gd2), which installed libraries in the following places:
/opt/local/include/gd.h
/opt/local/lib/libgd.dylib (link)
/opt/local/lib/libgd.la
/opt/local/lib/libgd.a
Here is my make file also:
dev: main.o
g++ -L/opt/local/lib -I/opt/local/include -lgd -lpng -lz -ljpeg -lfreetype -lm main.o -o heatmap
main.o: main.cpp
g++ -c main.cpp
So when I create my c++ app I add '#include "gd.h"', which throws:
main.cpp:4:16: error: gd.h: No such file or directory
If I set gd.h as an absolute path (as above)(not a solution, but was curious), I am thrown:
g++ -L/opt/local/include -L/opt/local/lib main.o -o heatmap
Undefined symbols:
"_gdImagePng", referenced from:
_main in main.o
"_gdImageLine", referenced from:
_main in main.o
"_gdImageColorAllocate", referenced from:
_main in main.o
_main in main.o
"_gdImageDestroy", referenced from:
_main in main.o
"_gdImageCreate", referenced from:
_main in main.o
"_gdImageJpeg", referenced from:
_main in main.o
ld: symbol(s) not found
So, I understand this means that ld can not find the libraries it needs (hence trying to give it hints with the "-L" values). So after giving g++ the -L hints and the absolute path in #include, I can get it to work, but I don't think I have to do this, how can I make g++/ld search int eh right places for the libraries?
Drew J. Sonne.
PS. using:
- OSX 10.6.2
- gcc version 4.2.1 (Apple Inc. build 5646) (dot 1)
EDIT:
Ok, so after taking into account stfanB and Michael's answer, I've recompiled gd into a local directory (libraries) and thus, I've changed that first line of my Makefile (I will def check out cmake) to g++ -L./libraries/lib -I./libraries/include -lgd -lpng -lz -ljpeg -lfreetype -lm main.o -o heatmap
But I'm still getting main.cpp:3:16: error: gd.h: No such file or directory
EDIT:
Thanks all for the answers, here's my final (working) makefile for anyone else who many want an answer:
dev: main.o
g++ -I./libraries/include -L./libraries/lib -lgd -lpng -lz -ljpeg -lfreetype -lm main.o -o heatmap
main.o: main.cpp
g++ -I./libraries/include -c main.cpp
| Rather than invoke g++ directly, I strongly advise you to use CMake (watch the CMake Google Techtalk if you'd like to learn more) as it will make your life way easier and greatly simplifies locating and linking against a variety of libraries. That said, I believe the problem with your invocation is that you have not specified the library, which you would do with -lgd. Your -L/opt/local/lib correctly tells g++ to look in /opt/local/lib, but you never told it what to look for. As for finding the appropriate header, you can use -I/opt/local/include to put /opt/local/include in the compiler's include search path.
If you were to heed my advice to use CMake, doing this would look like:
FIND_PACKAGE(GD2 REQUIRED)
INCLUDE_DIRECTORIES(${GD2_INCLUDE_DIRS})
LINK_DIRECTORIES(${GD2_LIBRARY_DIRS})
ADD_EXECUTABLE(heatmap main Heatmap_Map Heatmap_Point)
TARGET_LINK_LIBRARIES(heatmap ${GD2_LIBRARIES})
If you are interested in learning more about CMake, you might want to take a look at the C++ Application Project Template and C++ Library Project Template, which make use of the CMake build system. CMake is available through MacPorts via the command "sudo port install cmake".
In case you are not interested in installing CMake, I should also point out that there are some environment variables that you might be interested in knowing about to make your life easier, namely:
CPATH
LIBRARY_PATH
DYLD_FALLBACK_LIBRARY_PATH
The CPATH environment variable is much like the PATH environment variable (it is a colon separated list of directories), except that the directories in that variable will automatically be used by gcc and g++ as if they were specified on the commandline with the -I flag (i.e. headers will be searched in those paths). The LIBRARY_PATH is the equivalent except that it is as if the folders were given with -L (i.e. libraries will automatically be searched in that path). DYLD_FALLBACK_LIBRARY_PATH will be used by the dynamic linker (so you should probably include the paths from LIBRARY_PATH into this variable).
You can read more about the environment variables affecting gcc at the link.
|
2,497,151 | 2,497,191 | Can the C++ `new` operator ever throw an exception in real life? | Can the new operator throw an exception in real life?
And if so, do I have any options for handling such an exception apart from killing my application?
Update:
Do any real-world, new-heavy applications check for failure and recover when there is no memory?
See also:
How often do you check for an exception in a C++ new instruction?
Is it useful to test the return of “new” in C++?
Will new return NULL in any case?
| The new operator, and new[] operator should throw std::bad_alloc, but this is not always the case as the behavior can be sometimes overridden.
One can use std::set_new_handler and suddenly something entirely different can happen than throwing std::bad_alloc. Although the standard requires that the user either make memory available, abort, or throw std::bad_alloc. But of course this may not be the case.
Disclaimer: I am not suggesting to do this.
|
2,497,211 | 2,498,022 | How to profile multi-threaded C++ application on Linux? | I used to do all my Linux profiling with gprof.
However, with my multi-threaded application, it's output appears to be inconsistent.
Now, I dug this up:
http://sam.zoy.org/writings/programming/gprof.html
However, it's from a long time ago and in my gprof output, it appears my gprof is listing functions used by non-main threads.
So, my questions are:
In 2010, can I easily use gprof to profile multi-threaded Linux C++ applications? (Ubuntu 9.10)
What other tools should I look into for profiling?
| Edit: added another answer on poor man's profiler, which IMHO is better for multithreaded apps.
Have a look at oprofile. The profiling overhead of this tool is negligible and it supports multithreaded applications---as long as you don't want to profile mutex contention (which is a very important part of profiling multithreaded applications)
|
2,497,248 | 2,497,260 | How does one obtain the Windows installation date, without using WMI? | Not much to say about this question...
| It's stored in the registry under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion in the InstallDate key. The value is an integer number of seconds since 1/1/1970 (i.e. "Unix" time)
|
2,497,541 | 2,497,564 | C++ best practice: Returning reference vs. object | I'm trying to learn C++, and trying to understand returning objects. I seem to see 2 ways of doing this, and need to understand what is the best practice.
Option 1:
QList<Weight *> ret;
Weight *weight = new Weight(cname, "Weight");
ret.append(weight);
ret.append(c);
return &ret;
Option 2:
QList<Weight *> *ret = new QList();
Weight *weight = new Weight(cname, "Weight");
ret->append(weight);
ret->append(c);
return ret;
(of course, I may not understand this yet either).
Which way is considered best-practice, and should be followed?
| Option 1 is defective. When you declare an object
QList<Weight *> ret;
it only lives in the local scope. It is destroyed when the function exits. However, you can make this work with
return ret; // no "&"
Now, although ret is destroyed, a copy is made first and passed back to the caller.
This is the generally preferred methodology. In fact, the copy-and-destroy operation (which accomplishes nothing, really) is usually elided, or optimized out and you get a fast, elegant program.
Option 2 works, but then you have a pointer to the heap. One way of looking at C++ is that the purpose of the language is to avoid manual memory management such as that. Sometimes you do want to manage objects on the heap, but option 1 still allows that:
QList<Weight *> *myList = new QList<Weight *>( getWeights() );
where getWeights is your example function. (In this case, you may have to define a copy constructor QList::QList( QList const & ), but like the previous example, it will probably not get called.)
Likewise, you probably should avoid having a list of pointers. The list should store the objects directly. Try using std::list… practice with the language features is more important than practice implementing data structures.
|
2,497,726 | 2,497,816 | What makes this "declarator invalid"? C++ | I have Vertex template in vertex.h. From my graph.h:
20 template<class edgeDecor, class vertexDecor, bool dir>
21 class Vertex;
which I use in my Graph template.
I've used the Vertex template successfully throughout my Graph, return pointers to Vertices, etc. Now for the first time I am trying to declare and instantiate a Vertex object, and gcc is telling me that my 'declarator' is 'invalid'. How can this be?
81 template<class edgeDecor, class vertexDecor, bool dir>
82 Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const
83 {
84 /* Construct new Graph with apropriate decorators */
85 Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>();
86 span.E.reserve(this->E.size());
87
88 typename Vertex<edgeDecor,int,dir> v = new Vertex(INT_MAX);
89 span.V = new vector<Vertex<edgeDecor,int,dir> >(this->V.size,v);
90 };
And gcc is saying:
graph.h: In member function ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool) const’:
graph.h:88: error: invalid declarator before ‘v’
graph.h:89: error: ‘v’ was not declared in this scope
I know this is probably another noob question, but I'll appreciate any help.
| Igor is right. As for the following error:
graph.h:88: error: expected type-specifier before ‘Vertex’
... you probably need to say:
Vertex<edgeDecor,int,dir> v = new Vertex<edgeDecor,int,dir>(INT_MAX);
|
2,497,753 | 2,497,770 | C++ Variable declarable in function body, but not class member? | I want to create a C++ class with the following type:
It can be declared inside of a function.
It can be declared inside of a member function.
It can not be declared as a class member.
The use of this: think "Root" objects for a GC.
Is this possible in C++? In particular, I'm using g++. Willing to switch to clang. Either templates or macro solution fine.
Thanks!
| You could do it with a macro, perhaps:
#define MY_TYPE \
do { } while(0); \
RealType
void foo() {
MY_TYPE myvar;
myvar.Whatever();
}
This would only compile inside a function (because of the "do ... while" bit - though you'd get a really weird error message). It seems like one of those "evil" uses of macros that you would want to avoid, however...
|
2,497,943 | 2,498,084 | Tips Unit testing modal class in passive view pattern | I am new to unit testing. I have done unit testing on controller classes but have never tested modal class. I am using passive view pattern for my application.
I am using Cpp Unit test framework.
Any tips would be highly appreciated.
Thanks
Rahul
| You can create a base class that will be an interface for your modal class. Your modal class will inherit from this base class. The class(es) using the modal class will only know that base class.
For the unit tests, you implement another class, dedicated solely to unit testing, based on the base class (interface) and offering a controllable behavior. For instance, your unit test can create a class that will always return as if OK (or Cancel or Help) has been clicked. Or this test class can be made parameterizable.
This class will return immediately when asked to display the modal window so that the unit test won't stop.
The code receives a reference (or a pointer) to the base class, which will be an instance of the modal class in production, and an instance of the mock during unit testing.
The technique of passing a test class offering the same interface as the real class instead of an instance of the real class is known under the Dependency Injection name.
Look for M. Feathers' "the humble dialog box" article.
|
2,498,008 | 2,498,053 | In a C++ template, is it allowed to return an object with specific type parameters? | When I've got a template with certain type parameters, is it allowed for a function to return an object of this same template, but with different types? In other words, is the following allowed?
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool
print = false) const
{
/* Construct new Graph with apropriate decorators */
Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>();
/* ... */
return span;
};
If this is not allowed, how can I accomplish the same kind of thing?
| Allowed. Some corrections to your code sample:
template<class edgeDecor, class vertexDecor, bool dir>
Graph<edgeDecor,int,dir> *Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool
print = false) const
{
/* Construct new Graph with apropriate decorators */
Graph<edgeDecor,int,dir> *span = new Graph<edgeDecor,int,dir>();
/* ... */
return span;
};
|
2,498,009 | 2,498,054 | Best way to encrypt a directory of files? | I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.
How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?
Programming language doesn't matter. I am dictioned in all syntax.
|
How can I accomplish this, and WHAT IS
the BEST encryption way to do it, if
applicable?
tar and gzip the directory.
Generate a random bit stream of equal size to the file
Run bitwise XOR on the streams
Only truly secure method is a truly random one time pad.
|
2,498,072 | 2,498,357 | how to print correctly the handling thread on Windows? | Could someone please tell us on how to print correctly the handling thread in windows? Actually I tried several ways but it doesn't return the right number as in Unix-variant, as such e.g.:
cout << " with thread " << pthread_self << endl;
cout << " with thread " << pthread_self().p << endl;
Thanks for your replies:
| GetCurrentThread returns a "pseudohandle", not a valid thread handle. You should use "GetCurrentThreadId" instead (or ::GetCurrentThreadId()), and include windows.h, of course.
|
2,498,119 | 2,498,129 | How do I get a part of the a string in C++? | How do I get a part of a string in C++? I want to know what are the elements from 0 to i.
| You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/
// string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str="We think in generalities, but we live in details.";
// quoting Alfred N. Whitehead
string str2, str3;
size_t pos;
str2 = str.substr (12,12); // "generalities"
pos = str.find("live"); // position of "live" in str
str3 = str.substr (pos); // get from "live" to the end
cout << str2 << ' ' << str3 << endl;
return 0;
}
|
2,498,183 | 2,498,200 | Which to use - "operator new" or "operator new[]" - to allocate a block of raw memory in C++? | My C++ program needs a block of uninitialized memory and a void* pointer to that block so that I can give it to a third party library. I want to pass control of the block lifetime to the library, so I don't want to use std::vector. When the library is done with the block it will call a callback that I have to supply and that will deallocate the block. In C I would use malloc() and later free().
In C++ I can either call ::operator new or ::operator new[] and ::operator delete or operator delete[] respectively later:
void* newBlock = ::operator new( sizeOfBlock );
// then, later
::operator delete( newBlock );
Looks like both ::operator new and ::operator new[] have exactly the same signature and exactly the same behavior. The same for ::operator delete and ::operator delete[]. The only thing I shouldn't do is pairing operator new with operator delete[] and vice versa - undefined behavior. Other than that which pair do I choose and why?
| Use new with a single object and new[] with an array of objects. So, for example:
int* x = new int; // Allocates single int
int* y = new int[5]; // Allocates an array of integers
*x = 10; // Assignment to single value
y[0] = 8; // Assignment to element of the array
If all you are doing is allocating a memory buffer, then allocate an array of char as in:
int bufferlen = /* choose a buffer size somehow */
char* buffer = new char[bufferlen];
// now can refer to buffer[0] ... buffer[bufferlen-1]
However, in C++, you should really use std::vector for arbitrary arrays, and you should use std::string for character arrays that are to be interpreted or used as strings.
There is no reason to invoke ::operator new or ::operator new[] explicitly rather than using the ordinary syntax for these calls. For POD and primitive types (e.g. char) no initialization will take place. If you need to get a void* buffer, then simply use static_cast to convert char* to void*.
|
2,498,435 | 2,499,924 | Declaration of template class member specialization | When I specialize a (static) member function/constant in a template class, I'm confused as to where the declaration is meant to go.
Here's an example of what I what to do - yoinked directly from IBM's reference on template specialization:
===IBM Member Specialization Example===
template<class T> class X {
public:
static T v;
static void f(T);
};
template<class T> T X<T>::v = 0;
template<class T> void X<T>::f(T arg) { v = arg; }
template<> char* X<char*>::v = "Hello";
template<> void X<float>::f(float arg) { v = arg * 2; }
int main() {
X<char*> a, b;
X<float> c;
c.f(10); // X<float>::v now set to 20
}
The question is, how do I divide this into header/cpp files? The generic implementation is obviously in the header, but what about the specialization?
It can't go in the header file, because it's concrete, leading to multiple definition. But if it goes into the .cpp file, is code which calls X::f() aware of the specialization, or might it rely on the generic X::f()?
So far I've got the specialization in the .cpp only, with no declaration in the header. I'm not having trouble compiling or even running my code (on gcc, don't remember the version at the moment), and it behaves as expected - recognizing the specialization. But A) I'm not sure this is correct, and I'd like to know what is, and B) my Doxygen documentation comes out wonky and very misleading (more on that in a moment a later question).
What seems most natural to me would be something like this, declaring the specialization in the header and defining it in the .cpp:
===XClass.hpp===
#ifndef XCLASS_HPP
#define XCLASS_HPP
template<class T> class X {
public:
static T v;
static void f(T);
};
template<class T> T X<T>::v = 0;
template<class T> void X<T>::f(T arg) { v = arg; }
/* declaration of specialized functions */
template<> char* X<char*>::v;
template<> void X<float>::f(float arg);
#endif
===XClass.cpp===
#include <XClass.hpp>
/* concrete implementation of specialized functions */
template<> char* X<char*>::v = "Hello";
template<> void X<float>::f(float arg) { v = arg * 2; }
...but I have no idea if this is correct. Any ideas?
| Usually you'd just define the specializations inline in the header as dirkgently said.
You can define specializations in seperate translation units though if you are worried about compilation times or code bloat:
// x.h:
template<class T> struct X {
void f() {}
}
// declare specialization X<int>::f() to exist somewhere:
template<> void X<int>::f();
// translation unit with definition for X<int>::f():
#include "x.h"
template<> void X<int>::f() {
// ...
}
So yes, your approach looks fine. Note that you can only do this with full specializations, thus it is often impractical to do this.
For details, see e.g. Comeaus template FAQ.
|
2,498,443 | 2,499,701 | Login to a remote machine & accessing network resources | I want to access a file on remote machine(win2k3, 10.10.20.30), but i couldn't understand how to login to that machine in my program. is there any simple win api that takes network path, credentials and returns the handle?
i just want to access \10.10.20.30\c$\test.txt,
WNetAddConnection2, WNetAddConnection3 are little confusing. Any suggestion will be helpful.
sorry for not being very clear. I want to access a computer on same network(LAN).
I wanted to access a file that is not shared on other computer.
| If you have administrator rights, the solution is fairly simple. The C$ administrative share is available. You can call WNetAddConnection2 to create a local driveletter pointing to it. NETRESOURCE.dwType = RESOURCETYPE_DISK of course, .lpLocalName = NULL as you don't need it, .lpRemoteName = _T("\\\\10.10.20.30\\c$") (note the escaping of \ in C strings, it really starts with 4 of them). .lpProvider = NULL - let Windows figure the provider out.
Leave the username/password empty, and Windows will use your current user credentials. If those are indeed (network) administrator credentials, they're sufficient.
dwFlags should include CONNECT_TEMPORARY, as you're only interested in one file.
However, I think that (given sufficient credentials) it's easier to just call CreateFile("\\\\10.10.20.30\\c$\\test.txt") and let Windows deal with the details.
|
2,498,755 | 2,498,930 | How do I send floats in window messages | What is the best way to send a float in a windows message using c++ casting operators?
The reason I ask is that the approach which first occurred to me did not work. For the record I'm using the standard win32 function to send messages:
PostWindowMessage(UINT nMsg, WPARAM wParam, LPARAM lParam)
What does not work:
Using static_cast<WPARAM>() does not work since WPARAM is typedef'ed to UINT_PTR and will do a numeric conversion from float to int, effectively truncating the value of the float.
Using reinterpret_cast<WPARAM>() does not work since it is meant for use with pointers and fails with a compilation error.
I can think of two workarounds at the moment:
Using reinterpret_cast in conjunction with the address of operator:
float f = 42.0f;
::PostWindowMessage(WM_SOME_MESSAGE, *reinterpret_cast<WPARAM*>(&f), 0);
Using an union:
union { WPARAM wParam, float f };
f = 42.0f;
::PostWindowMessage(WM_SOME_MESSAGE, wParam, 0);
Which of these are preffered? Are there any other more elegant way of accomplishing this?
| Use reinterpret_cast< WPARAM &>(f). This cast is not restricted to pointers, it also works with references.
|
2,498,906 | 2,498,946 | Imbricated C++ template | I have the following pattern:
template <int a, int b>
class MyClass
{
public:
template <int c>
MyClass<a, c> operator*(MyClass<b, c> const &other) const;
};
// ../..
template <int a, int b> template <int c>
MyClass<a, c> MyClass<a, b>::operator*(MyClass<b, c> const &other) const //< error here
{
MyClass<a, c> result;
// ..do stuff..
return result;
}
It doesn't compile, the error message is
Error C2975. error C2975: 'dom' : invalid argument template for 'MyClass'
If I replace template <int c> by template <int c, int d> and use it accordignly, it works fine. But I want d to be the same value as b.
My questions:
Why the example doesn't work?
How can I enforce d to be the same than b?
Thanks.
| The following code compiles fine for me (as it should).
template <int a, int b>
struct MyClass
{
template <int c>
MyClass<a, c> operator*(MyClass<c, b> const &other) const;
};
template <int a, int b> template <int c>
MyClass<a, c> MyClass<a, b>::operator*(MyClass<c, b> const &other) const
{
MyClass<a, c> result;
return result;
}
int main()
{
MyClass<1, 2> a;
MyClass<3, 2> b;
a * b;
}
Note that in your code:
You are returning a reference to a temporary.
The operator * is not accessible from outside the class because it's private.
Please post real code and indicate the line casing the error.
|
2,498,912 | 2,499,451 | C/C++ method parameter hints in Eclipse | is there any way how to enable Eclipse to show hints for parameters of C/C++ functions.
When I press Ctrl + Shift + Space it shows only types of parameters but not the names.
And is there also any way Eclipse can show parameter hints automatically when ( is pressed?
Thanks for any advice.
| Are you using the CDT plugin? If so which version? The following applies to Eclipse 3.5 (Galileo) with the CDT plugin. If your setup is different then the rest of this answer may not be accurate.
Ctrl + Space brings up the type and names of parameters for me.
Looking through the preferences (Window -> Preferences -> C/C++ -> Editor -> Content Assist ) there's an Auto-Activation panel. There's 3 triggers available, ., :: and ->
Typing this-> and waiting 200ms brings up a list of auto-complete options. This list contains the methods and shows both the type and name of the parameters (if the name is available)
The same applies to foo. where foo is an object and bar-> where bar is a pointer.
If you're talking about when you're implementing a method, then the same applies. Foo:: + Ctrl + Space brings up the list of available items, including methods and shows parameter types and names.
|
2,498,978 | 2,499,421 | Loading and storing encryption keys from a config source | I am writing an application which has an authenticity mechanism, using HMAC-sha1, plus a CBC-blowfish pass over the data for good measure. This requires 2 keys and one ivec.
I have looked at Crypto++ but the documentation is very poor (for example the HMAC documentation). So I am going oldschool and use Openssl. Whats the best way to generate and load these keys using library functions and tools ? I don't require a secure-socket therefore a x.509 certificate probably does not make sense, unless, of-course, I am missing something.
So, do I need to write my own config file, or is there any infrastructure in openssl for this ? If so, could you direct me to some documentation or examples for this.
| This is the solution I am going for atm. Unless of course someone comes up with a better one, or one that solves my specific problem.
I will put three files in /etc/acme/auth/file1 file2 and file3, binary files with randomly generates numbers for the 2 keys and the ivec, and do the same in windows but under c:\etc\acme\auth.
|
2,499,108 | 2,499,174 | List login sessions on a mac | I'm writing an application that runs as a system daemon (root session) for Mac OSX 10.6. As part of this application, I need to list all the active graphical login sessions.
There is an (undocumented, but public) function called SessionGetInfo which will give me more information about a session with a known session Id, but I need a function that tells me the active session Ids on the system.
The ultimate goal here is for the daemon application to launch an agent in each graphical user session.
| If you're on Mac OSX 10.5+, according to this document from Apple you could use the utmpx API.
Some example code can be found here.
Hope this is helpful.
|
2,499,122 | 2,499,164 | Whats going on here can't you compare if(mychar1 == 'ä' || mychar2 == 'Ä') in C++? | Im trying to compare these two chars but on win 32 Visual Studio 2008:
if(mychar1 == 'ä' || mychar2 == 'Ä')
Erromess:
Debug Assertion Failed!
File:f\dd\vctools\crt_bld\self_x86\crt\src\xstring
Line 1575
Expression: string subscript out of range
| Works on my machine:
#include <iostream>
int main()
{
char mychar1, mychar2;
std::cin >> mychar1 >> mychar2;
if(!std::cin)
return 2;
if(mychar1 == 'ä' || mychar2 == 'Ä' )
return 1;
std::cout << "No!\n";
return 0;
}
Note that the error you quote ("string subscript out of range") implies that you try to access a character in a string at an invalid index. Something like my_str.at(10) (or, in a Debug build, my_str[10]), where my_str only has 10 characters. Since the code you showed doesn't access characters in strings, the error is in code you don't show.
Edit: The code you showed in a comment to your question does access characters in a string using operator[](). When you do string2[0], have you checked that the string isn't empty?
|
2,499,216 | 2,499,258 | What are the differences between break and exit? | Even I used break() and exit() statements many times, I am bit confused between them. I need to know exact meaning of both, when we should use them. Please explain with small example.
Thank you.
| break is a keyword that exits the current construct like loops. exit is a non-returning function that returns the control to the operating system. For example:
// some code (1)
while(true)
{
...
if(something)
break;
}
// some code (2)
In the above code, break exits the current loop which is the while loop. i.e. some code (2) shall be executed after breaking the loop.
For exit, it just gets out of the program totally:
// some code (1)
while(true)
{
...
if(something)
exit(0);
}
// some code (2)
You would get out of the program. i.e. some code (2) is not reached in the case of exit().
|
2,499,674 | 2,499,702 | c++: Is it possible to #include inside a function body? | I want to include a header file only if a certain function body is called?
Is this possible or recommended in C++?
| No.
You've got it a bit wrong; #include is not processed at run-time, at all. It's not possible to #include a file based on a program's execution characteristics; once the program executes its source is fixed (since it's already compiled).
|
2,499,842 | 2,499,968 | How to get statistical distributions out of C++ Code? | I want some help in programming a random generator for different types of distribution using C++ language. for the following:
Geometric distribution
Hypergeometric distribution
Weibull distribution
Rayleigh distribution
Erlang distribution
Gamma distribution
Poisson distribution
Thanks.
| The Boost Random Number library is very good. There's a simple example of how its distributions work at Boost random number generator.
|
2,499,895 | 2,500,544 | What's the purpose of having a separate "operator new[]"? | Looks like operator new and operator new[] have exactly the same signature:
void* operator new( size_t size );
void* operator new[]( size_t size );
and do exactly the same: either return a pointer to a big enough block of raw (not initialized in any way) memory or throw an exception.
Also operator new is called internally when I create an object with new and operator new[] - when I create an array of objects with new[]. Still the above two special functions are called by C++ internally in exactly the same manner and I don't see how the two calls can have different meanings.
What's the purpose of having two different functions with exactly the same signatures and exactly the same behavior?
| In Design and Evolution of C++ (section 10.3), Stroustrup mentions that if the new operator for object X was itself used for allocating an array of object X, then the writer of X::operator new() would have to deal with array allocation too, which is not the common usage for new() and add complexity. So, it was not considered to use new() for array allocation. Then, there was no easy way to allocate different storage areas for dynamic arrays. The solution was to provide separate allocator and deallocator methods for arrays: new[] and delete[].
|
2,500,109 | 2,578,467 | C++ printf std::vector | How I can do something like this in C++:
void my_print(format_string) {
vector<string> data;
//Fills vector
printf(format_string, data);
}
my_print("%1$s - %2$s - %3$s");
my_print("%3$s - %2$s);
I have not explained well before. The format string is entered by the application user.
In C# this works:
void my_print(format_string) {
List<string> data = new List<string>();
//Fills list
Console.WriteLine(format_string, data.ToArray);
}
my_print("{0} - {1} - {2}");
my_print("{2} - {1}");
| I have temporarly solved with this function:
string format_vector(string format, vector<string> &items)
{
int counter = 1;
replace_string(format,"\\n","\n");
replace_string(format,"\\t","\t");
for(vector<string>::iterator it = items.begin(); it != items.end(); ++it) {
ostringstream stm; stm << counter;
replace_string(format, "%" + stm.str(), *it);
counter++;
}
return format;
}
|
2,500,410 | 2,501,119 | Doxygen/C++: Global namespace in namespace list | Can I show the global namespace in the namespace list of the documentation generated with Doxygen? I have some functions which are extern "C", they appear in the documentation of the header file that declares them, but not in the namespace list and it gives the impression that they are not really there...
| As far as i know, this feature is still missing from Doxygen. One work-around that is not overly verbose is to use @defgroup MyGlobals and put the extern "C" functions in that group:
/*! @ingroup MyGlobals
* @{ */
// ... functions
/*! @} */
This adds the functions in an entry called MyGlobals on the tab Modules.
This blog entry presents a work-around using xrefs, but i personally find it too verbose.
|
2,500,521 | 2,500,691 | Getting libstdc++-v3/python | I am trying to download libstdc++-v3/python to enable pretty printing of stl containers. However, my provider returns: svn: Unknown hostname 'gcc.gnu.org' error. This is the command:
svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
Is there an alternative way to get this package?
| try http:// instead of svn://
that would be :
svn co http://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
|
2,500,525 | 2,501,380 | C++ app fails to initialize (0xc0000005), when using C# dll | I have a C# DLL, which I call from a native C++ programm.
As I use Qt and /clr compiler option did not work I followed this tutorial for a bridge.
So I have a VS2008 project (compiled with /clr), which links to the C# DLL and contains the bridge class and the native class, which exposes interfaces to my C++ programm. Another VS2008 project (no .net stuff) calls the native class (statically linked).
I had some issues, but now the programm at least compiles.
However, if I try to run this programm, I get a (0xc0000005) error on initialization, when I try to use the native class.
As this happens on initialization, I don't even see, which DLLs fail to initialize. All DLLs should be in the right place.
Any hints?
Thank you.
| The project, which called the native class was linked statically to my exe and this did not worked. I changed it to a DLL and now it seems to work.
I'll investigate a little more.
|
2,500,664 | 32,200,655 | What's the simplest way of defining lexicographic comparison for elements of a class? | If I have a class that I want to be able to sort (ie support a less-than concept), and it has several data items such that I need to do lexicographic ordering then I need something like this:
struct MyData {
string surname;
string forename;
bool operator<(const MyData& other) const {
return surname < other.surname || (surname==other.surname && forename < other.forename); }
};
This becomes pretty unmanageable for anything with more than 2 data members. Are there any simpler ways of achieving it? The data members may be any Comparable class.
| With the advent of C++11 there's a new and concise way to achieve this using std::tie:
bool operator<(const MyData& other) const {
return std::tie(surname, forename) < std::tie(other.surname, other.forename);
}
|
2,500,670 | 2,501,004 | Why this friend function can't access a private member of the class? | I am getting the following error when I try to access bins private member of the GHistogram class from within the extractHistogram() implementation:
error: 'QVector<double> MyNamespace::GHistogram::bins' is private
error: within this context
Where the 'within this context' error points to the extractHistogram() implementation. Does anyone knows what's wrong with my friend function declaration?
Here's the code:
namespace MyNamespace{
class GHistogram
{
public:
GHistogram(qint32 numberOfBins);
qint32 getNumberOfBins();
/**
* Returns the frequency of the value i.
*/
double getValueAt(qint32 i);
friend GHistogram * MyNamespace::extractHistogram(GImage *image,
qint32 numberOfBins);
private:
QVector<double> bins;
};
GHistogram * extractHistogram(GImage * image,
qint32 numberOfBins);
} // End of MyNamespace
| According to my GCC the above code does not compile because the declaration of extractHistogram() appears after the class definition in which it is friended. The compiler chokes on the friend statement, saying that extractHistogram is neither a function nor a data member. All works well and bins is accessible when I move the declaration to before the class definition (and add a forward declaration class GHistogram; so that the return type is known to the compiler). Of course the code for extractHistogram() should be written inside the namespace, either by
namesapce MyNameSpace {
// write the function here
}
or
GHistogram *MyNameSpace::extractHistogram( //....
|
2,500,677 | 2,500,724 | Making Global Struct in C++ Program | I am trying to make global structure, which will be seen from any part of the source code. I need it for my big Qt project, where some global variables needed. Here it is: 3 files (global.h, dialog.h & main.cpp). For compilation I use Visual Studio (Visual C++).
global.h
#ifndef GLOBAL_H_
#define GLOBAL_H_
typedef struct TNumber {
int g_nNumber;
} TNum;
TNum Num;
#endif
dialog.h
#ifndef DIALOG_H_
#define DIALOG_H_
#include <iostream>
#include "global.h"
using namespace std;
class ClassB {
public:
ClassB() {};
void showNumber() {
Num.g_nNumber = 82;
cout << "[ClassB][Change Number]: " << Num.g_nNumber << endl;
}
};
#endif
and main.cpp
#include <iostream>
#include "global.h"
#include "dialog.h"
using namespace std;
class ClassA {
public:
ClassA() {
cout << "Hello from class A!\n";
};
void showNumber() {
cout << "[ClassA]: " << Num.g_nNumber << endl;
}
};
int main(int argc, char **argv) {
ClassA ca;
ClassB cb;
ca.showNumber();
cb.showNumber();
ca.showNumber();
cout << "Exit.\n";
return 0;
}
When I`m trying to build this little application, compilation works fine, but the linker gives me back an error:
1>dialog.obj : error LNK2005: "struct TNumber Num" (?Num@@3UTNumber@@A) already defined in main.obj
Is there exists any solution?
Thanks.
| Yes. First, Don't define num in the header file. Declare it as extern in the header and then create a file Global.cpp to store the global, or put it in main.cpp as Thomas Jones-Low's answer suggested.
Second, don't use globals.
Third, typedef is unnecessary for this purpose in C++. You can declare your struct like this:
struct TNum {
int g_nNumber;
};
|
2,500,877 | 2,532,646 | count of distinct acyclic paths from A[a,b] to A[c,d]? | I'm writing a sokoban solver for fun and practice, it uses a simple algorithm (something like BFS with a bit of difference).
now i want to estimate its running time ( O and omega). but need to know how to calculate count of acyclic paths from a vertex to another in a network.
actually I want an expression that calculates count of valid paths, between two vertices of a m*n matrix of vertices.
a valid path:
visits each vertex 0 or one times.
have no circuits
for example this is a valid path:
alt text http://megapic.ir/images/f1hgyp5yxcu8887kfvkr.png
but this is not:
alt text http://megapic.ir/images/wnnif13ir5gaqwvnwk9d.png
What is needed is a method to find count of all acyclic paths between the two vertices a and b.
comments on solving methods and tricks are welcomed.
| Not a solution but maybe you can think this idea a bit further. The problem is that you'll need to calculate also the longest possible path to get all paths. The longest path problem is NP complete for general graphs, so it will get a very long time even for relative small graphs (8x8 and greater).
Imagine the start-vertex is in the top, left corner and the end vertex is in the lower, right corner of the matrix.
For a 1x2 matrix there is only 1 possible path
2x2 matrix => 2***1** paths => 2
3x2 matrix => 2***2** paths => 4
3x3 matrix => 2***4** + 2*2 paths => 12
3x4 matrix => 2***12** + 12 + 2 paths => 38
Everytime I combined the results from the previous calculation for the current number of paths. It could be that there is a close formular for such a planar graph, maybe there is even a lot of theory for that, but I am too stupid for that ...
You can use the following Java (sorry, I am not a c++ expert :-/) snippet to calculate possible paths for larger matrices:
public static void main(String[] args) {
new Main(3, 2).start();
}
int xSize;
int ySize;
boolean visited[][];
public Main(int maxX, int maxY) {
xSize = maxX;
ySize = maxY;
visited = new boolean[xSize][ySize];
}
public void start() {
// path starts in the top left corner
int paths = nextCell(0, 0);
System.out.println(paths);
}
public int nextCell(int x, int y) {
// path should end in the lower right corner
if (x == xSize - 1 && y == ySize - 1)
return 1;
if (x < 0 || y < 0 || x >= xSize || y >= ySize || visited[x][y]) {
return 0;
}
visited[x][y] = true;
int c = 0;
c += nextCell(x + 1, y);
c += nextCell(x - 1, y);
c += nextCell(x, y + 1);
c += nextCell(x, y - 1);
visited[x][y] = false;
return c;
}
=>
4x4 => 184
5x5 => 8512
6x6 => 1262816
7x7 (even this simple case takes a lot of time!) => 575780564
This means you could (only theoretically) compute all possible paths from any position of a MxM matrix to the lower, right corner and then use this matrix to quickly look up the number of paths. Dynamic programming (using previous calculated results) could speed up things a bit.
|
2,501,087 | 2,508,254 | Programming a VPN, Authontication stage - RFC not clear enough | I have a custom build of a Unix OS.
My task: Adding an IPSec to the OS.
I am working on Phase I, done sending the first 2 packets.
What I am trying to do now is making the Identification Payload.
I've been reading RFC 2409 (Apendix B) which discuss the keying materials (SKEYID, SKEYID_d, SKEYID_a, SKEYID_e and the IV making).
Now, I use SHA-1 for authontication and thus I use HMAC-SHA1 and my encryption algorithm is AES-256.
The real problem is that the RFC is not clear enough of what should I do regarding the PRF.
It says:
"Use of negotiated PRFs may require the
PRF output to be expanded due to
the PRF feedback mechanism employed by
this document."
I use SHA-1, does it mean I do not negotiate a PRF?
In my opinion, AES is the only algorithm that needs expention (a fixed length of 256 bit), so, do I need to expand only the SKEYID_e?
If you happen to know a clearer, though relible, source then the RFC please post a link.
| You cannot negotiate a PRF based solely on RFC2409, so don't worry about that. 3 key Triple-DES, AES-192, and AES-256 all require the key expansion algorithm in Appendix B. Many implementations have these, so testing interoperability should not be that hard.
|
2,501,171 | 2,501,202 | Storing objects in STL vector - minimal set of methods | What is "minimal framework" (necessary methods) of complex object (with explicitly malloced internal data), which I want to store in STL container, e.g. <vector>?
For my assumptions (example of complex object Doit):
#include <vector>
#include <cstring>
using namespace std;
class Doit {
private:
char *a;
public:
Doit(){a=(char*)malloc(10);}
~Doit(){free(a);}
};
int main(){
vector<Doit> v(10);
}
gives
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 ***
Aborted
and in valgrind:
malloc/free: 2 allocs, 12 frees, 50 bytes allocated.
UPDATE:
Minimal methods for such object are: (based on sbi answer)
class DoIt{
private:
char *a;
public:
DoIt() { a=new char[10]; }
~DoIt() { delete[] a; }
DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); }
DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;}
void swap(DoIt& rhs) { std::swap(a,rhs.a); }
};
Thanks, sbi, https://stackoverflow.com/users/140719/sbi
| Note that Charles has answered your question perfectly.
Anyway, as per the Rule of Three, your class, having a destructor, should have a copy constructor and an assignment operator, too.
Here's how I would do it:
class Doit {
private:
char *a;
public:
Doit() : a(new char[10]) {}
~Doit() {delete[] a;}
DoIt(const DoIt& rhs) : a(new char[10]) {std::copy(rhs.a,rhs.a+10,a);}
void swap(DoIt& rhs) {std::swap(a,rhs.a);}
DoIt& operator=(DoIt rhs) {swap(rhs); return *this;}
};
|
2,501,272 | 2,501,483 | Is there any algorithm for turning simple Haxe code into C/C++ code files? | I have simple Haxe app like
class Main
{
public static function main()
{
trace("hello world");
}
}
I know how to compile such app for windows (not as SWF but as app from pure C\C++ )(and you can see how here but be worned thay use hxcpp\0,4 ) The problem is - I do not want to compile app for Windows Vista or 7 or XP I want to get PURE C\C++ code (better in one place as one project) for for example compiling that code on windows mobile or where ever I want to.
So is there any algorithm for turning simple Haxe code into C/C++ code files?
| AFAICT hxcpp does generate C++ code which uses a platform specific library(Neko). the output is not windows specific.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.