question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,540,067 | 3,540,077 | Should I use string or char[]? | So I want to have a buffer with an array of structs like this:
EventItem
{
tag; // some string or array of characters to describe the value;
value; // some integer or something
}
The value can be anything like int32. What I am concerned about is the tag. If I have an array of these objects, and I make the tag a... | What you want is a std::string.
Not only because its c++ and not c, but also because operating on std::strings is much easier than on char[].
Also, the construction of your struct might be easier and more straightforward as well, avoiding copy of char[]
struct EventItem{
EventItem(const int_32 value,const std::stri... |
3,540,075 | 3,540,157 | Reference Counted Objects and multiple Allocators | This is a design question, assuming C++ and a reference counted object hierarchy. A lot of classes in my codebase derive from a common base class (ObjectBase), which implements retain() and release() methods to increase and decrease the reference count of an object instance.
Every instance of an object may be created o... | Have a look at this article: Overloading New in C++ . You could overload the new operator for ObjectBase so that it takes your allocator as a parameter and does the rest of the job:
void *ObjectBase::operator new(size_t size, Allocator *allocator) {
void *ptr = allocator->allocate(size);
// Hack to pre-initialize ... |
3,540,329 | 3,541,163 | c++ vectors erase check | Is there a way in C++ to check that erase succeeds?
I have two pieces of code that erase the same object. The first erased the object, then the second tries to erase it but doesn't find the object.
Any ideas?
for(long indexs=0; indexs < (long)Enemie1.vS2Enemie1.size(); indexs++)
{
if((vRegularShots[index].x>=Enemi... | You really want to use the Erase-Remove Idiom to do this.
|
3,540,488 | 3,541,012 | How to develop pear of PHP in C++ | I have used PHP a lot , and now i want to give back PHP community some contribution but for this I need help from experts ,
What i want to know is how to develop PHP pears in C++ or can suggest links or path way for it
| In case you want to develop an extension module for php in C/C++ take a look at PHP at the Core: A Hacker's Guide to the Zend Engine.
If you have existing C/C++ code you might also be interested in SWIG: SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level program... |
3,540,528 | 3,540,568 | Gecko XPCOM usage vs WebKit | I need to embed a web browser in C++ application. As well, I need to reach its javascript methods from Delphi components.
I know that for FF there is Gecko with XPCOM. Is there something like this for WebKit?
| WebKit first: there's project called Chromium embedded (Chromium is basically WebKit rendering engine and V8 Javascript engine), that has also Delphi support. After a quick look into headers, I did not find a way to access JS methods, but it allows executing javascript snippets in given frame:
// Execute a string of Ja... |
3,540,784 | 3,540,813 | Knowing if function is taking reference or value at runtime | So this is a purely academic question, mostly as its been a while since I've done anything too complex in C++. But is there any way to know if a method is taking a paramter as a reference or a value? This isn't important for pointers, as if you try to pass a non-pointer to a method that takes a pointer, you get a compi... | Yes. In any language it is possible to create a function that returns different results based on whether the function uses pass-by-value or pass-by-reference. This shouldn't be used in day-to-day programming, but it is useful for testing the compiler, testing an API, etc. Basically, call your function with a variable t... |
3,540,839 | 3,541,804 | _matherr does not get called when built into a DLL | I have a basic solution file (.sln) where I was able to reproduce a problem I have been facing recently.
It contains 3 projects:
1.) MathTest.lib - containing methods that might cause a mathematical error, like acos(1.1).
2.) MathTestDll.dll - calls the methods from the above lib.
3.) UnitTest.exe - calls the exported ... | It is explicitly mentioned in the documentation for _matherr:
For special error handling, you can
provide a different definition of
_matherr. If you use the dynamically linked version of the C run-time
library (Msvcr90.dll), you can replace
the default _matherr routine in a
client executable with a user-defi... |
3,540,841 | 3,540,883 | Prototype parameter names | In my header, I have a prototype declaration like this:
void move(int, int);
I can omit the parameter names, that's how I'm used to it from C. I do that so that I don't have to keep the parameter names in sync - it's extremely confusing if they differ between prototype and implementation.
Right now, I'm documenting al... | Surely if "names starting with __ are disallowed in C++", you shouldn't be using them in prototypes either :-) *a
I see two ways to do it.
One, you can ensure that the order of parameters in your comments always matches the order in your prototype.
Or, two, you could actually put the real names in your prototypes as we... |
3,540,891 | 3,540,916 | Calling virtual function in subclass from superclass | I know this question must have been covered endless of times, but I've searched the previous questions, and nothing seems to pop.
It's about inheritance and virtual functions i C++. I have a problem with calling virtual functions in subclasses from the superclass.
Let me give an example. Start of with three classes, wh... | The following prints "A::foo C::bar" as expected. Are you getting something different? B::bar is never called because C is the actual runtime type of the object. In C::bar, you could call B::bar explicitly by adding B::bar(); to its body.
#include <iostream>
using namespace std;
class A {
public:
void foo() { c... |
3,540,931 | 3,540,941 | Inline functions in C++ | Hii ,
I am a novice in C++. I did read about inline functions and understood them right. But this site says that "We get an 'unresolved external' error if we write the definition of an inline function in one .cpp file and call it from another file....why is that so ... ?
This can be done for normal functions right...Pl... | It's a language requirement. inline means that you may have the function defined in more than one translation unit but the definitions must be identical and that you must have a definition in every translation unit that uses the function.
Those are the rules. The rules allow (but don't require) the compiler to expand t... |
3,540,932 | 3,541,602 | Mixing Haskell and C++ | If you had the possibility of having an application that would use both Haskell and C++.
What layers would you let Haskell-managed and what layers would you let C++-managed ?
Has any one ever done such an association, (surely) ?
(the Haskell site tells it's really easy because Haskell has a mode where it can be compile... | The benefit of Haskell is the powerful abstractions it allows you to use. You're not thinking in terms of ones and zeros and addresses and registers but computations and type properties and continuations.
The benefit of C++ is how tightly you can optimize it when necessary. You aren't thinking about high-minded monads,... |
3,541,023 | 3,643,420 | Doxygen hide source files | I just started using Doxygen to generate documentation for my libraries and I found one minor glitch I can't get around.
In the tree view there's the file list and you can click on one of the files and then get the source code. I found a way to get rid of the file list but then I can't see the enums anymore.
Do you kn... | I'm relatively new to doxygen, but disabling SHOW_FILES and VERBATIM_HEADERS options seems to get rid of the source code lists.
|
3,541,110 | 3,541,197 | C++ : Multiple inheritance with polymorphism | (pardon the noob question in advance)
I have 4 classes:
class Person {};
class Student : public Person {};
class Employee : public Person {};
class StudentEmployee : public Student, public Employee {};
Essentially Person is the base class, which are directly subclassed by both Student and Employee. StudentEmployee emp... | StudentEmployee certainly is a subclass of Person. The problem is it is so twice: It indirectly inherits Person twice (once through Student and once through Employee) and that's why you get the "ambiguous base class" error. To make sure StudentEmployee only inherits Person once, you have to use virtual inheritance, lik... |
3,541,353 | 3,541,367 | Doxygen link to const function | I've got the following function prototype:
bool key_pressed(enum key key) const;
I documented it using doxygen. Now I have an overloaded version of that function that does the same, so I wanted to copy the doxygen comment like this:
/// @copydoc key_pressed(enum key) const
bool key_pressed(char key) const;
This does ... | /// @copydoc key_pressed(enum key) const
Should this not be (enum key key)? Not that I would advise using the same name for the input parameter as the enum name...
|
3,541,399 | 3,541,421 | postfix and prefix increment operator in a for loop |
Possible Duplicate:
Difference between i++ and ++i in a loop?
Can anyone explain what's the difference between those:
for(unsigned col = 0; col < n; ++col, num_to_fill >>= 1U)
{
for(unsigned row = num_to_fill; row < (1U << n); row += (num_to_fill * 2))
{
std::fill_n(&output[col][row], num_to_fill, 1... | It does not make any difference to the value of col within the loop - assuming col is a primitive value. If col was a class, the prefix and postfix '++' operators might be overloaded to do two different things, although I would consider it bad practice. Consider the following example:
#include <iostream>
using namespa... |
3,541,416 | 3,541,450 | Strange Multiple Definitions Error | I have something like this in my code:
namespace A {
namespace B {
void
GetLine(std::istream& stream, std::string& line)
{
line.clear();
while (stream.good()) {
std::getline(stream, line);
boost::trim(line);
if (not line.empty()) break;
}
boost::to_upper(line);
}
}
}
And I get... | You almost certainly included the code in multiple headers, rather than declaring in a header and defining in a source file. You need to declare the function inline, template it, or move the definition into a source file but leave the declaration in a header.
|
3,541,529 | 13,014,491 | Is there QPath::Combine in QT4? | I need a similar to .NET method for safely combining path parts without worrying for platform specifics of the path separator.
Is there such class and method in QT4?
Something like:
QPath::Combine
| There is not any function that can be used as direct replacement for Path.Combine() so you have to write it by your own.
You may do it in the hard way (handling everything by yourself) or simply use QDir::cleanPath():
QString pathAppend(const QString& path1, const QString& path2)
{
return QDir::cleanPath(path1 + QD... |
3,541,557 | 3,541,581 | Type condition in C++ template class problem | Using GCC 4.2.
I have this metatemplate for conditional type:
template <bool condition, typename Then, typename Else>
struct IF
{
typedef Then RET;
};
template <class Then, class Else>
struct IF<false, Then, Else>
{
typedef Else RET;
};
and when I use it like this:
template <typename T>
class Param
{
IF< ... | In the second case, what RET is, depends on the template type T. The compiler needs to be assured that it is going to be a type in all possible instantiations (and not perhaps a static member of some instantiation of IF). You do so with the typename keyword.
template <typename T>
class Param
{
typename IF< sizeof(i... |
3,541,571 | 3,541,669 | STL set of map iterators | I have an stl unordered_map and I would like to store references to elements in that map. I would like there to be no duplicate references. I thought I could create an set of iterators which pointed to elements. For one I wasn't sure that it would recognise , but even so I got some long template errors which I think... | Since you are trying to store the iterators in an unordered set, you don't need a comparison operator but rather a hash function.
I'm guessing, since each distinct iterator will be pointing to a distinct key, you can use the hash value of the key for hashing the iterator.
struct iterator_hash
{
size_t operator()(st... |
3,541,617 | 3,541,641 | having difficulties in reading two lines of code | How to analyze these two following lines of code?
w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0);
and
w += 30 + (i % 2 ^ i >= 8);
| Here is how to analyze it
int main(){
int w = 0;
int y = 400;
w += /* 28 + */ y % 4 == 0 && (y % 100 || y % 400 ==0);
int t1 = y % 100;
int t2 = y % 400;
int t3 = t1 | t2;
bool t4 = (y % 4);
int w1 = t3 & t4;
}
Note that t1 and t2, can be evaluated in any order
t3 will be eval... |
3,541,632 | 3,541,733 | Using make_shared with a protected constructor + abstract interface | Given an abstract interface and an implementation derived from that interface, where constructors are protected (creation of these objects only being available from a class factory - to implement a DI pattern), how can I make use of make_shared in the factory function?
For example:
class IInterface
{
public:
... | With VC10 the solution you linked to doesn't work - the construction of the instance of InterfaceImpl doesn't happen in make_shared, but in an internal type in std::tr1::_Ref_count_obj<Ty>::_Ref_count_obj(void).
I'd just make the Create() function a friend in your case and not use make_shared():
class InterfaceImpl : p... |
3,541,818 | 3,541,829 | Can UB cause several single-threaded app runs to produce different outputs? | Is it possible for code that meets the following conditions to produce different outputs for each run for the same input?
The code is single threaded, though
it does link against a thread-safe
runtime library.
There are no explicit calls to rand() or time() or their friends.
There are some heap memory allocations.
T... | "Undefined behavior" means that anything can happen. This also includes that different things might happen on each run of the program.
For example, if you use uninitialized memory it might be different from program run to program run what exactly that memory contains.
A simple example:
int main() {
char s[1024];
s[... |
3,542,030 | 3,542,043 | extending c++ string member functions | I had a need to do a case insensitive find and found the following code which did the trick
bool ci_equal(char ch1, char ch2)
{
return toupper((unsigned char)ch1) == toupper((unsigned char)ch2);
}
size_t ci_find(const string& str1, const string& str2)
{
string::const_iterator pos = std::search(str1. begin ( ),... | std::string is not made to be extended.
You could encapsulate an std::string into a class of yours and set those member functions in that class.
|
3,542,041 | 3,542,155 | How to know which user account runs a specific windows service? | How can I know, by using C++ code, which user runs a specific service? The program I need to write might run under a local administrator account, so I guess there won't be permissions problems.
Is it possible?
TIA.
| Depending on whether you need the user of the currently running service or the user specified in startup parameters of the service, see QueryServiceObjectSecurity and QueryServiceConfig functions in Windows API respectively.
|
3,542,497 | 3,542,584 | Problem by a reference variable of a template parameter | The following small example shows my problem:
template<class T> struct X
{
static void xxx(T& x) { }
static void xxx(T&& x) { }
};
int main(int argc, char** argv)
{
int x = 9;
X<int>::xxx(x); // OK.
X<int&>::xxx(x); // ERROR!
return 0;
}
Error message (GCC):
error: ‘static void X::xxx(T&&) [w... | The C++11 language standard has an explanation of how this works at §8.3.2[dcl.ref]/6 (reformatted for readability):
If a typedef, a type template-parameter, or a decltype-specifier denotes a type TR that is a reference to a type T,
an attempt to create the type "lvalue reference to cv TR" creates the type "lvalue ref... |
3,542,968 | 3,543,310 | OpenCV Python binds incredibly slow iterations through image data | I recently took some code that tracked an object based on color in OpenCV c++ and rewrote it in the python bindings.
The overall results and method were the same minus syntax obviously. But, when I perform the below code on each frame of a video it takes almost 2-3 seconds to complete where as the c++ variant, also bel... | Try using numpy to do your calculation, rather than nested loops. You should get C-like performance for simple calculations like this from numpy.
For example, your nested for loops can be replaced with a couple of numpy expressions...
I'm not terribly familiar with opencv, but I think the python bindings now have a nu... |
3,543,408 | 3,543,705 | Embed XUL backend in C | I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.
If it is possible, can you give me a link to an example application ? I saw something about libXul, is it needed ? where can i find it ?
TNX, Vertilka
|
I need to write a standalone (not under XULRunner) c/c++ application (Windows OS) that uses XUL as its backend GUI library.
The usual way to create a XUL GUI on top of a C++ application is by writing a XULRunner application with the C++ code wrapped in an XPCOM plugin.
You can make your application "stand-alone" by c... |
3,543,461 | 3,550,539 | How much is 32 kB of compiled code | I am planning to use an Arduino programmable board. Those have quite limited flash memories ranging between 16 and 128 kB to store compiled C or C++ code.
Are there ways to estimate how much (standard) code it will represent ?
I suppose this is very vague, but I'm only looking for an order of magnitude.
| The output of the size command is a good starting place, but does not give you all of the information you need.
$ avr-size program.elf
text data bss dec hex filename
The size of your image is usually a little bit more than the sum of the text and the data sections. The bss section is essentially... |
3,543,472 | 3,543,492 | C++/G++ hello world application issue, maybe compilation | I am trying to compile my first c++ file on windows with the g++ compiler...
My cpp file is the following -
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
I type in this on command prompt to get to the directory
cd C:\Users\Mark
Then to compile my program I do
g++ hell... | What you did looks correct, but if you start the program by double clicking it in Windows, the new command prompt will be closed once it is finished. Since you already have a command prompt open for compilation, try to start the program from there, too:
g++ hello.cpp -o hello.exe
hello.exe
|
3,543,608 | 3,543,664 | Why does this segfault? | for(ItemTemplateListIterator iter = item_template_list.begin(); iter != item_template_list.end(); ++iter) {
int id = iter->first;
string description = iter->second->description;
some_file_stream << id << endl;
some_file_stream << description << endl;
}
Where item_template_list is a map of <int, MyClas... | What very likely happened is that the object pointers that you stored in the map are not valid anymore (because the memory was deallocated elsewhere). Attempting to access a deallocated memory area causes a segfault. Not valid is meaning either NULL or having a so-called "dangling pointer".
Maybe also you are modifying... |
3,543,697 | 3,543,766 | skipping vector position when pushing_back | I'm reading data from a file into a vector of strings called data. And to this data vector I push_back a new string through my main called output_string. Output_string is just a combination of the arguments passed in through command line. After doing all that I write back to my file(update the file with the new string)... | What might be happening is that originally, the file contents are the string:
"bob\n"
"jack\n"
"snack" // no line feed
which, line-by-line, is "bob", "jack", and "snack". When you write out these lines along with "john" endl, the contents of the file are:
"bob\n"
"jack\n"
"snack\n"
"john\n" // line feed
You might be ... |
3,543,725 | 3,543,928 | Should exceptions be chained in C++? | I just finished work on a C++-program where I've implemented my own exceptions (although derived from std::exception). The practice I've applied when one exception causes a chain reaction, propagating the error upwards and giving rise to other exceptions, is to concatenate the error message at each appropriate step acr... | It is necessary to copy the data out of an exception object, into a chain, if you want it to outlive the catch block that receives it, aside from rethrow by throw;. (Which includes, for example, if that catch block exits through a throw obj;.)
This can be done by putting data to be saved on the heap, and implementing s... |
3,543,783 | 3,543,858 | What is the C++ analog of C# byte[]? | What is the C++ (and or visual-C++) analog of C# byte[]?
| The closest equivalent type in C++ would be a dynamically created array of "unsigned char" (unless you're running on a processor that defines a byte as something other than 8 bits).
So for example
in C#
byte[] array = new byte[10];
in C++
unsigned char *array = new unsigned char[10];
|
3,543,835 | 7,894,169 | TNonblockingServer, TThreadedServer and TThreadPoolServer, which one fits best for my case? | Our analytic server is written in c++. It basically queries underlying storage engine and returns a fairly big structured data via thrift. A typical requests will take about 0.05 to 0.6 seconds to finish depends on the request size.
I noticed that there are a few options in terms of which Thrift server we can use in t... | Requests that take 50-600 milliseconds to complete are pretty long. The time it takes to create or destroy a thread is much less than that, so don't let that factor into your decision at this time. I would choose the one that is easiest to support and that is the least error-prone. You want to minimize the likelihood o... |
3,544,028 | 3,544,050 | Is there a way to know the name of class from which a method of an object is being called in C++? | Suppose in a method MA() of class A, a method MB() of class B is being called after creation of an object. Is there a way to know in MB() the name of the class and the method from which it is being called in C++ ??
| What you are talking about is a Stack Trace.
Stack Trace definition:
The stack trace is a useful debugging
tool that you'll normally take
advantage of when an exception has
been thrown. It provides information
on the execution history of the
current thread, displaying the names
of the classes and methods w... |
3,544,245 | 3,544,343 | Turning on linker flags with CMake | When generating VS2010 targets with CMake, I would like the /LTCG flag turned on (only for release + releasewithdebinfo if possible, but its okay if its on for debug builds). How do I modify the linker flags? add_definitions() doesn't work because that only modifies compiler flags. And yes, I have wrapped it in if(MSVC... | You can modify the linker flags in MSC using #pragma comment(linker, ...)
However, if you'd like to do it in the build process with cmake, here are the names you need to know:
CMAKE_EXE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
(Thanks to Cmake.org).
|
3,544,263 | 3,544,280 | Most common idiom for intra-process communciation on Windows? | I have a very simple interface which needs to communicate between processes. It's currently implemented in a very simple manner (all single proc):
bool GetFoo(struct Foo *outFoo);
bool GetBar(struct Bar *getBar);
Such as:
Foo foo;
if (!GetFoo(&foo))
{
ReportError();
}
GetFoo fills out the "Foo" data structure wi... | You have many choices, but in my personal experience the most popular/easy to use ones are: sockets & pipes.
See here for all IPC options available for Windows.
|
3,544,359 | 3,544,910 | Is it possible to create an image with C++? | Can you create a PNG, GIF, etc with C++ on windows?
If it's possible, how? For an example how can you make a png image just one solid color.
Just a "hello world" example would be great...
| When someone asks you about Hello world, just say Hello world ...
#include "opencv/cxcore.h"
#include "opencv/cv.h"
#include "opencv/highgui.h"
int _tmain(int argc, _TCHAR* argv[])
{
cv::Mat image(480, 640, CV_8UC3);
cv::putText(image, "Hello world", cvPoint(320, 200),
CV_FONT_HERSHEY_SIMPLEX, 1, cvSc... |
3,544,405 | 3,544,486 | Trade off between a recursive mutexes V a more complex class? | I've heard that recursive mutexs are evil but I can't think of the best way to make this class work without one.
class Object {
public:
bool check_stuff() {
lock l(m);
return /* some calculation */;
}
void do_something() {
lock l(m);
if (check_stuff()) {
/* ...... | If you need to expose check_stuff as public (as well as do_something which currently calls it), a simple refactoring will see you through without repeating any calculations:
class Object {
public:
bool check_stuff() {
lock l(m);
return internal_check_stuff(l);
}
void do_something() {
... |
3,544,491 | 3,544,517 | The PeekMessage function in C++ and named pipes | Regarding:
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)
If hWnd is NULL, PeekMessage retrieves
messages for any window that belongs
to the current thread, and any
messages on the current thread's
message queue whose hwnd value is NULL
(see the MSG structure). Therefore if
hWnd is NULL, both window messages an... | Definitely not. Named pipes do not send window messages.
The thread messages in this context are special and have nothing to do with named pipes.
Use MsgWaitForMultipleObjects instead.
CODE SAMPLE:
void MessageLoop(HANDLE hNamedPipe)
{
do {
DWORD res = MsgWaitForMultipleObjects(1, &hNamedPipe, INFINITE, QS_... |
3,544,572 | 3,544,609 | Can I use the reverse geocoding server side, e.g. with C# or C++? | Can I use the reverse geocoding server side, e.g. with a C# or C++?
EDIT: I get some list of longititudes and latitudes from GPS Mouse, And I need to find all the corresponds addresses and save it to database. I am not interested to show on a map.
| As long as you display the results on a google map and stay within 2,500 requests per day, sure (100,000 if you have Google Maps API Premier). Note, though, and I quote from here:
Note: the Geocoding API may only be
used in conjunction with a Google map;
geocoding results without displaying
them on a map is pro... |
3,544,627 | 3,544,702 | eclipse cdt relative include path? | Hey all. I've downloaded and moved the Xerces (v3.1.1) source here: /usr/include/xerces and I can see the source in the project explorer like this:
MyCppProject
Binaries
Includes
[...] // some other directories
xerces
dom
[...] // some other directories
And, here's my simple C++ code:
#include <xercesc/util/... | From what you state in your question it looks like your using the folder name 'xercesc' instead of 'xerces' in your include path.
try
#include <xerces/util/PlatformUtils.hpp>
The include directive will look in all of the directories in the include path and try to find the file specified. So if you specified a folder c... |
3,544,795 | 3,544,798 | Catch a run-time exception | Following fails to catch a exception
int *i; //intentionally uninitialized
try {
*i = 6;
}
catch (const runtime_error e) {
cout << "caught!" << endl;
}
is it actually catching a runtime error or an exception?
| The line *i = 6; does not throw a runtime_error; it results in undefined behavior.
The uninitialized pointer will be dereferenced and your program will try to write the value six to wherever it points (if it points anywhere). This results in undefined behavior. In most cases, this means your program will either cra... |
3,544,824 | 3,544,838 | Using declaration (Derived class) | struct B1{
int d;
void fb(){};
};
struct B2 : B1{
using B1::d;
using B1::fb;
int d; // why this gives error?
void fb(){} // and this does not?
};
int main(){}
Is it because, B1::fb() is treated as B1::fb(B1*) and B2::fb() treated as B2::fb(B2*)? That is, does the implicit paramete... | The C++ standard (C++03 §7.3.3/12) explains:
When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).
In your example, B2::fb() hides... |
3,544,965 | 3,545,075 | Usage of tellp in C++ | I have some misunderstanding about the tellp and seekg functions. For example, when I run the following code.
#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
int main(){
string s("in Georgia we are friends to each other");
ofstream out("output.txt");
for (int i=0; i<s.length()... | tellp gives the current position of the put pointer.
outfile.seekp (pos-7) statement moves the put pointer 7 bytes backwards from the its current position.
In your example, it was pointing beyond the string "This is an apple"
If you do pos-7,
it goes to the location where 'n' letter is present.
It overwrites the string... |
3,545,080 | 3,545,124 | C++ and Java : Use of virtual base class | I have some doubts while comparing C++ and Java multiple inheritance.
Even Java uses multiple, multi-level inheritance through interfaces - but why doesnt it use anything like a virtual base class as in C++ ? Is it because the members of a java interface are being ensured one copy in memory (they are public static fin... | 1) Java interfaces dont have attributes. One reason for virtual base classes in c++ is to prevent duplicate attributes and all the difficulties associated with that.
2) There is at least a slight performance penalty for using virtual base classes in c++. Also, the constructors become so complicated, that it is advised... |
3,545,102 | 3,545,410 | How to enumerate volumes on Mac OS X? | I am not very proficient in Mac OS X programming, but I am working on a Qt application which needs info about the storage devices. Basically a list of hard drives and USB thumb drives.
The end result should be like a vector which contains the following info for each device:
string: Label
string: Mount point
string: Dev... | This should get you most of what you're looking for:
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSArray *vols = [ws mountedLocalVolumePaths];
NSFileManager *fm = [NSFileManager defaultManager];
for (NSString *path in vols)
{
NSDictionary* fsAttributes;
NSString *description, *type, *name;
BOOL... |
3,545,249 | 3,545,389 | What is the difference between C++ memory management and .NET memory management? | What is the difference between C++ memory management and .NET memory management ?
| In C++, you can either allocate objects with static storage so they are around for the whole program, allocate them on the stack when they are local to a function (in which case they are destroyed when the containing block exits), or allocate them on the heap (in which case they are only destroyed when you say so by ex... |
3,545,259 | 3,545,291 | I need an optimal algorithm to find the largest divisor of a number N. Preferably in C++ or C# | I am currently using the following code but its very slow for large numbers
static int divisor(int number)
{
int i;
for (i = number / 2; i >= 1; i--)
{
if (number % i == 0)
{
break;
}
}
... | First thought you can find the smallest divisor d (not equal to 1 of course), then N/d will be the largest divisor you're looking for.
For example if N is divisible by 3 then you'll need 2 iterations to find the answer - in your case it would be about N/6 iterations.
Edit: To further improve your algorithm you can i... |
3,545,369 | 3,545,443 | Porting code which requires default char to be unsigned to a code-base which does not have this requirement | i have gone through the numerous questions regarding signed/unsigned char. I understand there are three distinct char types in C++. Currently i have a large code-base which is compiled with Visual Studio - the "default char unsigned" setting is set to "No". Now i'm supposed to add a particular project to our code-base ... | Um, holy crap. Can you tell us where this code came from so we can avoid it? :)
My first instinct would be to build the code as a separate library that your existing project links to, and be careful when you interface with it. Not knowing the exact nature of the code in question, I don't know if that's feasible.
If the... |
3,545,450 | 3,545,463 | How to initialize a shared_ptr that is a member of a class? | I am not sure about a good way to initialize a shared_ptr that is a member of a class. Can you tell me, whether the way that I choose in C::foo() is fine, or is there a better solution?
class A
{
public:
A();
};
class B
{
public:
B(A* pa);
};
class C
{
boost::shared_ptr<A> mA;
boost::shared_ptr<B>... | Your code is quite correct (it works), but you can use the initialization list, like this:
C::C() :
mA(new A),
mB(new B(mA.get())
{
}
Which is even more correct and as safe.
If, for whatever reason, new A or new B throws, you'll have no leak.
If new A throws, then no memory is allocated, and the exception aborts y... |
3,545,655 | 3,545,670 | which one to choose for future , c++ or python2.x/3.x | since last four years i had been coding in c/c++, but those lenthy programs made me sick of them.
then i got to know about python, and i have learned the basics.
python seams to be more flexible and powerful than c++...
But i want to know is python realy better than c++?
if yes/no in what ways , please explain.
since i... | Python is completely different than C/C++, so it's hard to compare. Python lets you write clear, concise programs and very quickly develop software at the price of performance. It lets you be very productive and in many cases program performance is less concern, than programmer performance.
There are many existing prog... |
3,545,887 | 3,928,656 | Fortify throws error while scanning Visual Studio project | I'm trying to run Fortify on a Visual Studio 2008 project. The project builds successfully on its own. When I try to analyze the project with Fortify using the Visual Studio integrated controls, the project builds successfully but an error message is thrown. Here's the output from Fortify console:
Fortify SCA...
Runnin... | OK, I think this is a known issue with C/C++ translation on VS2010. The workaround I found is:
Open a Visual Studio x86 Command Prompt
Change to the KindleExport.sln's directory
Run:
sourceanalyzer -b kindleexport devenv KindleExport.sln /REBUILD
Run:
sourceanalyzer -b kindleexport -scan -f KindleExport.fpr
|
3,546,004 | 3,546,024 | C++ function pointers and presetting arguments | Say I have a function f(a, b, c). Is it possible to create function pointers g and h such that when you use g and h they use a predetermined value for one of the arguments?
For example (*g)(b, c) would be equivalent to f(1, b, c) and (*h)(b, c) would be equivalent to calling f(2, b, c).
The reason why I am doing this i... | I don't see why you can do this if you have defined the function g points to as
void gfunc(int b, int c) {
f (1, b, c);
}
g = &gfunc;
The better way to do this in C++ is probably using functors.
|
3,546,054 | 3,546,585 | How do I run a single test with UnitTest++? | How do I run a single test with UnitTest++ ?
I am running UnitTest++ out of the box as is. My main function looks like:
int main()
{
printf("diamond test v0.1 %s\n\n",TIMESTAMP);
diamond::startup();
UnitTest::RunAllTests();
diamond::shutdown();
printf("press any key to continue...");
getc(stdin);
}
F... | try this as your main() for unittest (I actually put this in a file and added that to the unittest library, so that when linking to the library the executable automatically uses this main(). very convenient.)
int main( int argc, char** argv )
{
if( argc > 1 )
{
//if first arg is "suite", we search for suite n... |
3,546,184 | 3,546,871 | COM Server hang- detection and resolution | I have an application that sends requests to an out of proc COM server whom handles the requests and sends them back to the requesting application.
The client application is really in control of the start-stop of this Out-of-Proc COM server and determines its lifetime so to say.
Because this application has many hund... | You need to design all calls in the COM server in such way that they all end in some reasonably short time. Once a new call arrives from the client COM spawns a separate thread and dispatches a call onto that thread. There's no reliable way to interrupt the call - the call needs to end on itself (just return). You achi... |
3,546,340 | 3,546,582 | what is the expected behavior? | Below is a purely academically invented class hierarchy.
struct X{
void f1();
void f2();
void f3();
};
struct Y : private X{
void f4();
};
struct Z : X{
};
struct D : Y, Z{
using X::f2;
using Z::X::f3;
};
int main(){}
I expected using declaration for X::f2 to be ambi... | I don't think that any of these are ill-formed. First, for using X::f2, X is looked up, and this will unambiguously yield the class type X. Then f2 in X is looked up, and this is unambiguous too (it is not looked up in D!).
The second case will work for the same reason.
But if you call f2 on a D object, the call will b... |
3,546,438 | 3,546,537 | C++: Updating pointers in deep copy (efficiently) | My question is best illustrated with a code sample, so let's just start off with that:
class Game
{
// All this vector does is establish ownership over the Card objects
// It is initialized with data when Game is created and then is never
// changed.
vector<shared_ptr<Card> > m_cards;
// And then w... | Store the pointers as indexes.
As you say they all point to m_Cards which is a vector that can be indexed (is that correct English?).
Either you do that only for storing and convert them back to pointers at loading.
Or you may think of using indices generally instead of pointers.
|
3,546,735 | 3,547,085 | Different template error format in GCC? | GCC has a very verbose format for certain template error messages:
... some_class<A,B,C> [with int A = 1, int B = 2, int C = 3]
Any chance to make it show something like:
... some_class<1,2,3>
| You will lose track from what template the specialization comes from:
template<int A, int B> class X {
void f();
};
template<int A> class X<A, 2> {
void f();
};
int main() {
X<1, 2>().f();
X<2, 1>().f();
}
GCC outputs
m.cpp: In function 'int main()':
m.cpp:6:12: error: 'void X<A, 2>::f() [with int A = 1]' is... |
3,546,779 | 3,547,248 | How to find interfaces of an ActiveX control? | Given an instance of an ActiveX control, how do I enumerate it's interfaces? (I'd like to get the names of the interfaces).
| Like others have mentioned, the only way is to QueryInterface for all possible interfaces. And this is exactly what the Microsoft tool OleView does for you.
|
3,547,548 | 3,548,322 | gtkmm statusicon quits after creation | I have to create a simple application that displays an icon in the systray and a menu from which you can do some operations.
the problem is that statusicon is closed immediately after creation. What's missing?
I put the sleep to make sure it was created. for 3 seconds something appears in systray, even if it is not the... | You're not running a main loop at all, so no input events can be handled and the program exits after constructing the tray. What you want to do is delete the sleep, and then in your main() function, add the following line right before the return:
Gtk::Main::run();
Then, when you want the application to quit (generall... |
3,547,601 | 3,551,236 | Convert Objective-C code to C++ for detecting user idle time on OS X | I'm developing Qt/C++ application and I need simple function that retrive me User idle time in seconds on Mac OS X.
I found this code for detection User idle time.
#include <IOKit/IOKitLib.h>
/**
Returns the number of seconds the machine has been idle or -1 if an error occurs.
The code is compatible with Tiger/10.4 ... | You just need to add IOKit.framework in the list of linked frameworks. Think of a framework as a bundle of shared libraries and associated resources. IOKit.framework is at
/System/Library/Frameworks/IOKit.framework
I don't know how to do that in a Qt project; the project should have a list of extra frameworks which y... |
3,547,828 | 3,547,877 | I am trying to create an array of objects inside a header file which is failing (Starting C++ Programmer) | EDITED BELOW FOR UPDATES!!!
Thank you for the help, please by all means point out ALL mistakes , I don't care if it sounds rude or mean or whatever, emo junk. Just give it to me straight so I can understand what is going wrong.
Hi everyone!
I am a rookie C++ programmer trying to learn and gain some IRL exp for C++.
I a... | @user428435. Three things:
8x8 is 64, not 36
What kind of problems are you having? If a compilation error, what is the error? Often careful reading of the errors can help you solve your problems. If the code compiles and runs, what does it do that you don't expect it to do?
You probably meant
Tile* tileList_ptr[36];
|
3,547,886 | 3,549,874 | c++ sorting by depth using only a matrix. Possible? | If I have a std::vector of objects containing a rotated / translates matrix, is there a way I can use that matrix to calculate a Z position so that I can sort the objects by depth?
| Short answer :
sort along matrix[3][2], which is the z position (in world space) of your object's center.
Long answer :
In homogeneous coordinates, a position is (x,y,z,1) ( as opposed to a direction which is (x,y,z,0), as we will see later )
To transform your point from one space to another, you multiply it by the t... |
3,548,032 | 3,548,050 | Unconditionally Kill a process (Windows) | In C++ is there a way to unconditionally kill a process?
No matter what state this process is in.
I know about TerminateProcess, but it can still fail. What if you don't want it to fail.
Like when you kill a process in Task Manager, it dies; no matter what. That's the kind of killing I'm looking for.
| Not every process can be killed from Task Manager. This depends both on permissions and on process state. Some processes, hung in winsock can't be killed (and even Task Manager will hang).
|
3,548,290 | 3,548,376 | Using QGraphicsScene subclass with ui? | I have implemented signals for mousePressEvent() in a QGraphicsScene subclass, but I can't figure out how to use the class in a UI. I can add a QGraphicsView widget to my UI, but how do I then access the scene?
GraphicsScene *scene = new QGraphicsScene(this);
// Add pixmap, etc
ui->graphicsView->setScene(scene);
// Her... | In your example: use the scene pointer you already have:
connect(scene, SIGNAL(clicked(QPoint)), this, SLOT(someSlot(QPoint));
Alternatively, if you don't have the pointer laying around anymore, use this function:
connect(ui->graphicsView->scene(), SIGNAL(clicked(QPoint)), this, SLOT(someSlot(QPoint));
(untested, but... |
3,548,348 | 3,548,617 | Is it good to link a shared library against other shared libraries? | I have an application X which uses shared libraries A,B and C. Shared library C also uses some symbols from Shared library A. Application X is linked against A and B during compile time and it does dlopen to load C at run time.
My question is:
Is it a good idea to link C against A during link time or leave the symbol r... | Your option 1. But it does not work that way.
You link C with A.
As A is a dynamic lib this will do nothing phsically.
It verifies that all dependencies will be satisfied by A at runtime.
At runtime when you dlopen() the shared lib C
It will open C and if you had not already linked against A it would also open A
But s... |
3,548,516 | 3,548,550 | Templated Class has a Circular Dependency | I have two classes. One is a management class, which stores a bunch of worker classes. The workers are actually a templated class.
#include "worker.h"
class Management {
private:
worker<type1> worker1;
worker<type2> worker2;
...
};
The problem arises due to the fact that the templated c... | If no actual members of Management are referred by worker.inl (i.e. only pointers/references to Management), you could forward declare it:
class Management;
Worker::Worker(){
Management* mgmt1; // fine
Management& mgmt2; // fine
//mgmt1 = new Management(); // won't compile with forward declaration
//mg... |
3,548,797 | 3,548,831 | How to declare a variable in header file to be used in two .cpp? | My target module is an executable to be built from X.cpp and Y.cpp, both these two files need a common .h file:
extern HANDLE hPipe;
extern IMediaSample *pSave = NULL;
But when I build the module, I got an error saying :
Y.obj : error LNK2005: "struct IMediaSample * pSave" (?pSave@@3PAUIMediaSample@@A) already defined... | extern IMediaSample *pSave = NULL;
This is not just a declaration. This will define pSave to NULL. Since both .cpp include the .h, this variable will be defined in 2 translation units, which causes the conflict.
You should just rewrite it as
extern IMediaSample *pSave;
in the .h, then add IMediaSample *pSave = NULL; ... |
3,548,881 | 3,548,966 | Why are my local dlls taking forever to load after setting _NT_SYMBOL_PATH? | I've setup _NT_SYMBOL_PATH and have pointed it to
srv*c:\symbols*http://msdl.microsoft.com/download/symbols
When starting the debugger, I notice that the Windows related dlls load quickly. However, our company's dlls are taking a god awful long time to load. When I get rid of _NT_SYMBOL_PATH, restart visual studio, t... | Visual Studio searches _NT_SYMBOL_PATH before any paths configured inside Visual Studio. This is a "feature" of the debugging engine. This means that Microsoft's symbol servers will be searched for your symbols.
In Visual Studio 2010, they've made this explicit by (if it's set) including _NT_SYMBOL_PATH in the Debuggin... |
3,549,101 | 3,549,280 | Identifying endian related problems | I recently learned about endianness and am still having difficulty identifying problem areas.
Here is a snippet of code that uses data loaded from a binary file (a Dxt texture). I am uncertain if endianness could cause problems in this situation, such as the width, height, and the hexadecimal comparison. What things do... | Generally speaking, endianness only matters if your data is travelling over some physical interface (e.g. across a network, or to a file), where it may have originated from a platform with a different native endianness. It also occurs if you're trying to do "clever" things with pointer casts, e.g. int a = 0xABCD; char... |
3,549,255 | 3,549,281 | How to find the depth of each node in std::map? | If I construct, my own binary tree, then I can find the depth of each node.
The sample code is as follows
template<class datatype>
void binary_node<datatype>::printNodeWithDepth(int currentNodeDepth)
{
if ( left )
left->printNodeWithDepth(currentNodeDepth+1);
std::cout << value << " and the depth is " ... | std::map is not guaranteed to be a b-tree, it is just guaranteed to have at least as good runtime complexity. To open the door for other potential implementations, the interface does not include functions for inspecting this kind of implementation details. :)
|
3,549,377 | 3,549,418 | Designing a frontend/backend system in C++? | I'm about to write a program in C++, but I'm unsure as to how to go about it. I want to create a program that can be used with a command line frontend but also a GUI frontend as I don't want to bind a user to a specific interface such as a widget toolkit for dependencies' sake.
How would be the best way to do this? I k... | You implement your program's algorithms in a library, carefully avoiding any UI stuff. The API to your algorithms is specified in header files.
Then you can write several applications that use this library, one implementing a GUI front end and one a command line interface. They include the headers and compile against ... |
3,549,540 | 3,549,665 | Google Test Fixtures | I'm trying to understand how the Google Test Fixtures work.
Say I have the following code:
class PhraseTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
phraseClass * myPhrase1 = new createPhrase("1234567890");
phraseClass * myPhrase2 = new createPhrase("1234567890... | myPhrase1 and myPhrase2 are local to the setup method, not the test fixture.
What you wanted was:
class PhraseTest : public ::testing::Test
{
protected:
phraseClass * myPhrase1;
phraseClass * myPhrase2;
virtual void SetUp()
{
myPhrase1 = new createPhrase("1234567890");
myPhra... |
3,549,632 | 3,549,935 | QGraphicsScene subclass is ignoring mouse press events | I have a UI and a QGraphicsScene subclass GraphicsScene that implements mousePressEvent(), however mouse clicks are being ignored.
ui->setupUi(this);
scene = new GraphicsScene(this);
scene->addPixmap(QPixmap::fromImage(someImage));
ui->graphicsView->setScene(scene);
connect(scene, SIGNAL(clicked(QPoint)), this, SLOT(so... | mos was right about the function signature. The function should have been:
void GraphicsView::mousePressEvent(QGraphicsSceneMouseEvent *event) {
emit clicked(event->pos());
}
rather than
void GraphicsView::mousePressEvent(QMouseEvent *event) {
emit clicked(event->pos());
}
|
3,549,635 | 3,549,655 | Is there a reason fopen() wouldn't work after several hundred opens? | Hey, for this piece of code, the person who wrote the system communicates data between processes using textfiles. I have a loops that looks (for all intents and purposes) like this:
while (true)
{
//get the most up-to-date info from the other processes
pFile = fopen(paramsFileName, "r");
// Do a bunch of stuff with... | You're hitting the open file / file descriptor limit for your OS. It should run forever if you do fclose(pFile) in your loop.
|
3,549,807 | 3,549,814 | Preprocessor checking defined | I can check predefined value like:
#ifdef SOME_VAR
// Do something
#elif
// Do something 2
#endif
If I have to check 2 values instead of 1. Are there any operator:
#ifdef SOME_VAR and SOME_VAR2
// ...
#endif
Or I have to write:
#ifdef SOME_VAR
#ifdef SOME_VAR2
// At least! Do something
#endif
#endif... | The standard short-circuiting and operator (&&) along with the defined keyword is what is used in this circumstance.
#if defined(SOME_VAR) && defined(SOME_VAR2)
/* ... */
#endif
Likewise, the normal not operator (!) is used for negation:
#if defined(SOME_VAR) && !defined(SOME_OTHER_VAR)
/* ... */
#endif
|
3,549,900 | 3,553,128 | "Error deleting file: Permission denied" with remove in C++ | When I compile and run my C++ program that deletes a file called example.txt (below)
#include <stdio.h>
int main ()
{
if( remove( "example.txt" ) != 0 )
perror( "Error deleting file" );
else
puts( "File successfully deleted" );
return 0;
}
It comes out like this...
cd c:\Users\Mark\Desktop
C:\Users\Ma... | I guess std::remove() takes the path as a parameter. So we need to specify the entire path as a parameter for remove function.
eg: remove("home/xxx/example.txt");
|
3,549,982 | 3,550,044 | Vista/7 compile and XP/2000 execution issues with OpenProcess in C++ | I've been using OpenProcess with PROCESS_ALL_ACCESS rights for the following functions:
-EnumProcessModules
-GetModuleFileNameEx
-ReadProcessMemory
-WriteProcessMemory
which works fine on Windows Vista/7. However, in Windows XP/2000, it won't open the process with PROCESS_ALL_ACCESS because according to the MSDN librar... | Find the location of your #include <windows.h> directive and make it look like this:
#define _WIN32_WINNT 0x500 // Target Windows 2000
#include <windows.h>
|
3,550,068 | 3,550,197 | Is there a data structure with these characteristics? | I'm looking for a data structure that would allow me to store an M-by-N 2D matrix of values contiguously in memory, such that the distance in memory between any two points approximates the Euclidean distance between those points in the matrix. That is, in a typical row-major representation as a one-dimensional array of... | Given the requirement that you want to store the values contiguously in memory, I'd strongly suggest you research space-filling curves, especially Hilbert curves.
To give a bit of context, such curves are sometimes used in database indexes to improve the locality of multidimensional range queries (e.g., "find all items... |
3,550,685 | 3,551,381 | How to suspend variable assignment with boost::bind or boost::lambda? | I want to suspend a void() function that sets a stack variable to true. How can I do this?
bool flag = false;
boost::function<void()> f = ...;
f();
assert(flag);
This is, obviously, toy code that demonstrates the problem. My attempt at this, using bind, was bind<void>(_1 = constant(true), flag);, but this yields a com... | To use boost::bind, you'd need to make a function that sets a boolean to true, so you can bind to it:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/ref.hpp>
void make_true(bool& b)
{
b = true;
}
int main()
{
using namespace boost;
bool flag = false;
// without ref, calls wi... |
3,550,701 | 3,551,146 | Current Directory in XML | I am converting some environment variables to property sheets for some C++ projects. This way when the projects are used from the branch or the trunk in SVN we don't have to use a junction to switch between the branch and trunk.
My property sheet, paths.vsprops, is in this format:
<?xml version="1.0" encoding="Windows-... | You can obtain the path to the current VCPROPS file by fetching the $(MSBuildThisFileDirectory):
<PropertyGroup>
<MyProjectPath>$([System.IO.Path]::GetFullPath( "$(MSBuildThisFileDirectory)" ) )</MyProjectPath>
</PropertyGroup>
This MSFT blog has tons of info/tricks for doing things like this.
Have fun!
|
3,550,792 | 3,550,832 | Com Initialization Error 0x80040154 loading c# COM Object with c++ Program | I'm working on my first COM project that is importing a c# DLL with a C# COM Wrapper class into a C++ native code application. Our application is based on the CSRegFreeCOMServer VS2008 sample project from Microsoft's All-In-One Framework. Our system is using - VS2008, .Net3.5, boost 1.4.2 and Qt 4.6.2.
This applica... | 0x80040154 is REGDB_E_CLASSNOTREG. That is, class not registered.
The COM couldn't find (in the registry) the class factory with CLSID = __uuidof(Fields).
|
3,550,860 | 3,551,035 | Function pointer in parameter | I need to make a function which adds a function pointer to map. It would be something like this:
bool RegisterFunction (string name, FunctionPointer function).
But I have problem with calling it, because I don't know how to pass function to it instead of result of function (when I call this as here:
RegisterFunction (... | Run is a non-static member function, not a normal function so either you are registering something of the wrong type or you need to change your typedef to refer to a pointer-to-member.
E.g.
typedef CVariable (Parser::*FunctionPointer) (std::string);
Then the correct way to form a pointer-to-member would be:
RegisterFu... |
3,550,978 | 3,551,034 | Lifecycle of objects passed by reference to STL containers | I'm an experienced coder, but am still relatively new to the STL, and have just come across this problem:
As far as I'm aware, STL containers aren't meant to copy the objects which they contain, or otherwise affect their lifecycles, yet experimentally I'm seeing different results.
In particular, string classes, which a... |
As far as I'm aware, STL containers
aren't meant to copy the objects which
they contain
Okay, let's stop right there. STL containers do copy their contents, frequently. They copy them when they're inserted, they copy them when the container is resized either automatically or explicitly, and they copy them when th... |
3,551,125 | 3,551,151 | C++ FILE pointer to stdout? | I'm writing a program and I want the user to be able to specify whether the output is written to a file or to stdout. Until this point, my program has been using printf commands, so I was hoping to simply change the commands to fprintf commands, but my compiler is shouting at me because obviously, they are not the sam... | stdout is a FILE*, so you can simply use:
FILE* fp = stdout;
|
3,551,174 | 3,551,192 | Appended '= x' after a method declaration in c++ | In C++, when a method is declared, I've noticed that sometime the method may have an assignement appended to it.
Could anyone tell me what this is?
For example:
virtual void MyMethod () = 0;
What doe the '= 0' mean. :)
Thanks everyone !!!
| It means it's a pure virtual function, i.e. no actual definition of it is available in this class and it must be overridden in a subclass. It's not actually an assignment as such, zero is the only value you can "assign".
And this is C++ syntax; in C# the same would be accomplished with the abstract keyword.
|
3,551,213 | 3,551,233 | Printing PDF to HDC (MFC device context) | I'm modifying a C++ application and I'd like to add the ability to print and existing PDF using the MFC printing logic (OnPrint...)
Is there any method to print a PDF into the MFC? Now I'm converting the PDF to a BMP but sometimes the quality is not so great.
| Unless something's changed recently you need a 3rd party library to print PDF files. One direction you can take is to convert to PS and then use ghostscript to translate to printer speak. Ghostscript also has the power to convert PDF to PS.
|
3,551,362 | 3,551,480 | OpenGL: How to select correct mipmapping method automatically? | I'm having problem at mipmapping the textures on different hardware. I use the following code:
char *exts = (char *)glGetString(GL_EXTENSIONS);
if(strstr(exts, "SGIS_generate_mipmap") == NULL){
// use gluBuild2DMipmaps()
}else{
// use GL_GENERATE_MIPMAP
}
But on some cards it says GL_GENERATE_MIPMAP is suppor... | If drivers lie, there's not much you can do about it. Also remember that glGenerateMipmapEXT is part of the GL_EXT_framebuffer_object extension.
What you are doing wrong is checking for the SGIS_generate_mipmap extension and using GL_GENERATE_MIPMAP, since this enum belongs to core OpenGL, but that's not really the pro... |
3,551,386 | 3,551,434 | Strange error for member function declaration | Below is something that did happen to me and I couldn't get what's wrong. My coworker and me screwed our heads around this. It was in a cross-platform library using the cross-platform toolkit wxWidgets on Windows
#include <wx/wx.h>
class Graph {
public:
// ...
// main1.cpp:4:10: error: expected identifier before ... | WinGDI.h ln 640: #define GetYValue(cmyk) ((BYTE)((cmyk)>> 8))
Gotta love windows.h
This is why I recommend AGAINST using camel case for most things.
|
3,551,733 | 3,551,866 | LLVM automatic C++ linking | In some of the LLVM tutorials I'm seen where it's fairly easy to bind C function into a custom language based on LLVM. LLVM hands the programmer a pointer to the function that can be then be mixed in with the code being generated by LLVM.
What's the best method to do this with C++ libraries. Let's say I have a fairly c... | In my LLVM code, I create extern "C" wrapper functions for this, and insert LLVM function declarations into the module in order to call them. Then, a good way to make LLVM know about the functions is not to let it use dlopen and search for the function name in the executing binary (this is a pain in the ass, since the ... |
3,551,935 | 3,551,976 | How to return the name of a variable stored at a particular memory address in C++ | first time posting here after having so many of my Google results come up from this wonderful site.
Basically, I'd like to find the name of the variable stored at a particular memory address. I have a memory editing application I wrote that edits a single value, the problem being that every time the application holding... | Compile and generate a so called map file. This can be done easily with Visual-C++ (/MAP linker option). There you'll see the symbols (functions, ...) with their starting address. Using this map file (Caution: has to be updated each time you recompile) you can match the addresses to names.
This is actually not so easy ... |
3,551,999 | 3,552,030 | What is (double (^)(int))foofoo | There is an example on cdecl that goes (double (^)(int))foofoo means cast foofoo into block (int) returning double.
What does it mean to cast foofoo into a "block" of int? What does the symbol ^ exactly mean in this context. Usually it is bitwise XOR.
| It's a GCC extension made by Apple, and implemented also in Clang. Blocks are small unnamed functions and that syntax is the type of a block. See Block Language Spec.
|
3,552,094 | 3,552,116 | c++ uint , unsigned int , int | Hi I have a program that deals alot with vectors and indexes of the elements of these vectors, and I was wondering:
is there a difference between uint and unsigned int
which is better to use one of the above types or just use int as I read some people say compiler does handle int values more efficiently, but if I use... |
C++ defines no such type as uint. This must be "your" type, i.e. a type defined in your code or some third party library. One can guess that it is the same as unsigned int. Could be unsigned long int though or something else. Anyway, you have to check it yourself.
It is a matter of personal style. I, for example, beli... |
3,552,135 | 3,552,210 | Does C++11 provide hashing functions for std::type_info? | I'm still working on a good solution to my One-Of-A-Type Container Problem -- and upon reflection I think it would be nice to be able to just use something like a std::map<std::type_info, boost::any>. Unfortunately, std::type_info does not define an operator<, and I think it'd be unreasonable for it to define one.
Howe... | The fact that type_info is not less-than comparable isn't as much a problem for using it as a map key as the fact that type_info is non-copyable. :-)
In C++03, type_info has a before() member function that provides an ordering of type_info objects.
In C++11, type_info has a hash_code() member function (C++11 §18.7.1/7... |
3,552,344 | 3,552,358 | Compile Error in VS2010 while testing LinkedLists | I'm doing some tests to a LinkedList, that has two pointers: one point to the next item in the list and the other point to a random node within the list.
Here is the code:
struct Node
{
Node* pNext; // a pointer to the next node in the list
Node* pReference; // a pointer to a random node within the list
i... | This bit is not valid C++:
return new Node()
{
number = n->number,
pNext = duplicateList(n->pNext),
pReference = duplicateList(n->pReference)
};
Change it to this:
Node* pNode = new Node();
pNode->number = n->number;
pNode->pNext = duplicateList(n->pNext);
pNode->pReference = duplicateList(n->pReference);
r... |
3,552,372 | 3,552,415 | Is it possible to enter the terminate_handler twice? | I have some clean up in a terminate_handler and it is possible to throw an exception. Do I need to worry about catching it to prevent recursive calls to the terminate_handler? With gcc, it seems this can't happen and we just go into abort. Is that true of the standard or is the behavior undefined?
| A terminate handler is not allowed to return (§18.6.3.1/2); it must end the program (the default handler calls abort()). If it consisted of:
void my_terminate()
{
throw 5;
}
You'd get undefined behavior, because you would leave the function (because the exception propagates) without having terminated the program.... |
3,552,677 | 3,552,926 | Why this thread safe queue, creates a deadlock? | I've written my own version of thread safe queue. However, when I run this program, it hangs/deadlocks itself.
Wondering, why is this locks/hangs forever.
void concurrentqueue::addtoQueue(const int number)
{
locker currentlock(lock_for_queue);
numberlist.push(number);
pthread_cond_signal(&queue_availability... | Reformulating spong's comment as an answer: your locker class should NOT be copying the pthread_mutex_t by value. You should use a reference or a pointer instead, e.g.:
class locker
{
public:
locker(pthread_mutex_t& lockee): target(lockee)
{
pthread_mutex_lock(&target);
}
~locker()
{
... |
3,552,931 | 3,552,995 | WaitForSingleObject not work | Please see the code below:
#include <windows.h>
int main(int argc, char* argv[])
{
HANDLE _mutex = ::CreateMutex(NULL, FALSE, "abc");
if (!_mutex)
throw std::runtime_error("CreateMutex failed");
if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForS... | If you want a synchronization primitive that behaves like you've described you can use an auto-reset event instead.
#include <windows.h>
#include <stdexcept>
#include <stdio.h>
int main(int argc, char* argv[])
{
HANDLE _mutex = ::CreateEvent(NULL, FALSE, TRUE, NULL);
... |
3,553,000 | 3,553,019 | Are there any good Wiimote APIs (C/C++) out there that include Wii Motion Plus? | Hello I was looking around on the internet and I was unable to find anything concrete. I would like to find a good Wiimote API (in C or C++) that also implements usage of the Wii Motion Plus accessory. If anyone knows of any good ones it would be greatly appreciated. Thanks.
| I use WiiYourself.
You might need to adapt one thing or another, such as the connection timeout, but it works quite well.
Take also a look at WiiBrew's Wiimote page
and Wiimote driver page.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.