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
5,365,619
5,365,644
Returning null from function which returns a C++ object
I'm doing an example from Head First Object Oriented Analysis and Design, but I'm coding in C++ and I don't know how to write the equivalent of "return null" from java. Guitar getGuitar(string serialNumber) { for (vector<Guitar*>::iterator it = guitars.begin(); it != guitars.end(); ++it) { if ((*it)->...
Java references are like C++ pointers. So if you're returning a reference to an existing Guitar instance or null, then making your function return a Guitar* is probably what you want. By contrast what your code is actually doing is returning a new Guitar which is a copy of the existing instance. By comparison returning...
5,365,683
5,365,926
Breaking down a string and using keybd to send characters
I have searched the internet for a good system for emulating keypresses in C++. I want to send a string to another program but as far as I can see the GenerateKey function can only send one at a time. I created code to break a string down and send each letter individually but sometimes the number of a specific letter i...
This sort of approach is really complicated (you have to manage state of SHIFT, CONTROL, and ALT, convert special characters to ALT+0xyz combos) and if the user changes keyboard focus in the process, keys can go to the wrong window. Using SendMessage(WM_SETTEXT) or SendMessage(EM_REPLACESEL) you could send a whole stri...
5,365,689
5,365,714
C++ Overload Static Function with Non-Static Function
I would like to print two different things depending on whether a function is called statically with Foo::print() or from an instance of Foo foo; foo.print(); EDIT: Here is a class definition that definitely does not work, as answered by a few people already. class Foo { string bla; Foo() { bla = "nonstatic"; }...
No, it is directly prohibited by the standard: ISO 14882:2003 C++ Standard 13.1/2 – Overloadable declarations Certain function declarations cannot be overloaded: Function declarations that differ only in the return type cannot be overloaded. Member function declarations with the same name and the same parameter typ...
5,365,731
5,365,790
load multi-dimensional array into a data file in C++
In C++, how to implement the following functionality? Thanks. Assume in a program, I can get a matrix A = [1,2;2,1]. How to save it in an independent data file, e.g., data1. Secondly, how to load this file data1 into my another program 2 as a matrix A.
Struct for C++ File I/O binary file sample struct WebSites { char SiteName[100]; int Rank; }; to write void write_to_binary_file(WebSites p_Data) { fstream binary_file("test.dat",ios::out|ios::binary|ios::app); binary_file.write(reinterpret...
5,365,817
5,365,840
conditionally enabling constructor
Here is how I can conditionally enable a constructor of a class : struct Foo { template<class T> Foo( T* ptr, boost::enable_if<is_arithmetic<T> >::type* = NULL ) {} }; I would like to know why I need to do the enabling via a dummy parameter. Why can I not just write : struct Foo { template<class T> ...
You can on any other function but the constructor, because then you can modify the function name including the template arguments. Foo foo; foo.Method<T>(); With a constructor, though, the constructor name never appears in your expression, so there's no place to explicitly put the template parameter. You have to dedu...
5,365,941
5,814,272
Is boost::interprocess::shared_ptr threadsafe (and interprocess-safe)?
I want to share data between threads, and have it automatically deleted when the last user is done with it. This seems to work, most of the time, using boost::interprocess::shared_ptr in a boost::fixed_managed_shared_memory segment: but not always. So, is boost::interprocess::shared_ptr thread (and interprocess) -safe?...
The reference count used in boost::interprocess:shared_ptr is implemented using an atomic counter defined in boost/interprocess/detail/atomic.hpp with the refcount logic mainly implemented by boost/interprocess/smart_ptr/detail/sp_counted_base_atomic.hpp. The intent is to have the refcount be handled in a thread (and ...
5,366,080
5,366,094
ClassType Conversions - operator + ambiguous
In the following, I'm expecting obj to be converted to an int but why does it returns operator + ambiguous in the following? class MyClass { public: MyClass(int X = 0, double Y = 0):x(X), y(Y){} operator int() const { return x; } operator double() const { return y; } private: int x; double y; };...
Because both conversions are equivalent, it's ambiguous. Remember that the C++ language directly defines + for arguments of double and int, there is no standard conversion involved. So neither of these functions is better than the other: double operator+ (double, int) -- requires one user-defined conversion and no st...
5,366,171
5,366,199
Visual C++ 2010 code completion
I've been using c# for a while and I've noticed it had code prediction for your code and "resolves" for using's to functions. I'm working with visual c++ now and I noticed it has no code prediction and it doesn't have any "resolve" to any missing include. Is this a setting you have to enable in visual c++? Or do you h...
You don't get all the Intellisense features in VC++ that you get in C# or other managed languages. I would recommend getting Visual Assist from Whole Tomato as this considerably improves the IDE. You can check out a free eval copy I think.
5,366,359
5,366,363
c++ pointer reference confusion
struct leaf { int data; leaf *l; leaf *r; }; struct leaf *p; void tree::findparent(int n,int &found,leaf *&parent) This is piece of code of BST. I want to ask. why leaf *&parent Why we need "reference mark" here? parent is also a leaf, why can't I just use leaf* parent? cod...
You are passing the pointer parent in by reference, so that you can modify that pointer: parent=q; If you passed the pointer in by value, the modifications would be to a copy of the pointer that expires at the end of the function.
5,366,397
5,366,446
Setting an instance of an object to another one from inside, using this = new Foo()?
I am working with a hash table and to rehash it, I am simply putting all the values into a new hash table, and then setting the executing instance to this new hash table. I wasn't sure going into it if that was possible, so I just want to confirm if this is the case. I am trying: Foo *new_foo = new Foo(); ... delete th...
Program cannot modify this to point to a different object. this is a constant pointer ( i.e., T* const ). this = new_foo; // incorrect. what's the best/standard way for copying allocated arrays? Using *a = *b; doesn't copy the entire array. You are just copying the value at first index of b to first index of a. Use s...
5,366,774
5,398,246
Image Manipulation Library / API for Modifying Faces
I'm looking for an image manipulation library, preferably in .NET, that makes it easy to recognize and manipulate faces in images. Is there a library out there that does this?
There is OpenCV (Open Source Computer Vision), which is a is a library of programming functions for real time computer vision. I'm not familiar with it, so I don't know if it will make "easy to recognize and manipulate faces in images", but you can give it a look. It's not in .Net, but you tagged your question with C+...
5,367,090
5,367,126
Seg fault after calling destructor successfully or calling empy destructor. C++
I am very sorry that I am not able to provide more details of my code, since I am taking over another project. The class structures are very complicated and I am unable to reproduce the issue using an easy example. Essentally if I delete an object, all the statements in the destructor was executed successfully, but as...
One possible cause is that another object tries to access p after it got deleted. Update You could try and run your code through valgrind. Depends a little on how well you can isolate the problem before hand. My guess so far would be that you do something bad inside your class (like constructing an object and passing p...
5,367,152
5,367,302
How do I print the address of a method pointer in C++?
For example: struct A { void m() { } }; void stream_print() { void(A::*p)(void) = &A::m; std::cerr << p << std::endl; } void printf_print() { void(A::*p)(void) = &A::m; fprintf(stderr, "%p", p); } The stream_print() function always prints "1", which is obviously not what I want. The printf_print does not com...
Member function pointer is generally an object with non-trivial internal structure. Which is why you can't print it using tools intended for printing primitive types. Casting the pointer to void * is not a viable approach, since the size of member pointer is generally larger than sizeof(void *). Forcefully casting it t...
5,367,214
5,367,377
Any simple VAD implementation?
I'm looking for some C/C++ code for VAD (Voice Activity Detection). Basically, my application is reading PCM frames from the device. I would like to know when the user is talking. I'm not looking for any speech recognition algorithm but only for voice detection. I would like to know when the user is talking and when he...
There are open source implementations in the Sphinx and Freeswitch projects. I think they are all energy based detectors do won't need any kind model. Sphinx 4 (Java but it should be easy to port to C/C++) PocketSphinx Freeswitch
5,367,515
5,367,583
how to call a C++ dll exported function from c#
This is the first time I'm trying to mix c# an unmanaged C++ so this might be a very simple question , but I don't get it. I need to call some functions from a C++ dll into C# code. Here is the code for the dll project: the .h file : #pragma once #include <iostream> #if defined FIRSTDLL_EXPORTS #define DECLDIR __d...
The default calling convention for DLLImport is stdcall, but the default of your C++ code is cdecl. The error message you have seen is what is shown when the calling conventions don't match. The parameter stack cleanup requirements are different for these two calling conventions, and the P/Invoke marshaller detects an...
5,367,629
5,367,642
How can I combine some functors to generate a `isOdd` function?
How can I combine several functors to generate a isOdd functor? equal_to modulus bind2nd ... int nums[] = {0, 1, 2, 3, 4}; vector<int> v1(nums, nums+5), v2; remove_copy_if(v1.begin(), v1.end(), back_inserter(v2), isOdd); v2 => {0, 2, 4}
Using just the primitives provided in the standard libraries, this is actually surprisingly difficult because the binders provided by bind1st and bind2nd don't allow you to compose functions. In this particular case, you're trying to check if x % 2 == 1 Which, if you consider how the <functional> primitives work, is ...
5,367,663
5,371,535
Windows SDK parameter annotations
I am wondering if its important to use the the annotations when doing Windows development in C++? For instance, #include <windows.h> int WINAPI WinMain( __in HINSTANCE hInstance, __in HINSTANCE hPrevInstance, __in LPSTR lpCmdLine, __in int nCmdShow ){ return 0; } This can be written as: #include <w...
You must be working from an older version of the SDK. Version 7.0 declares the arguments like this: WinMain ( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in LPSTR lpCmdLine, __in int nShowCmd ); Note the __in_opt annotation, it marks the argument as optional, indicating that pass...
5,367,674
5,367,826
What does the error "non-placement deallocation function"?
I am getting the following error while compiling the serna-free package: build/buildd-serna-free_4.3.0.20110221-2-i386-pAsDoD/serna-free-4.3.0.20110221/ sfworks/common/RefCntStorage.h:76:10: error: non-placement deallocation function 'static void StringPrivate::RefCntData<E>::operator delete(void*,StringPrivate::size...
I think that the problem comes from this wording in the spec: If class T does not declare such an operator delete but does declare a member deallocation function named operator delete with exactly two parameters, the second of which has type std::size_t (18.1), then this function is a usual deallocation function This...
5,367,707
5,367,761
Invalid initialization error
I have a class with a private member std::set<Segment*> mSegments and the following method: std::pair<iterator, iterator> getSegments() { return boost::tie(mSegments.begin(), mSegments.end()); } and I get the following error: invalid initialization of non-const reference of type std::_Rb_tree_const_iterator<Segme...
I think that your problem is that you should probably be using make_pair here instead of tie. The point of tie is to allow functions that return tuples to have the return value assigned to multiple values at once. For example, if Get3DPoint returns a tuple<int, int, int>, then you could write int x, y, z; tie(x, y, z...
5,367,897
5,367,969
Confusion in continuing the Project Related to C Syntax Analyser
My target is to make a program (using C++) which would take C source code as input and check for "SYNTAX ERRORS ONLY". Now for this, do i need to know about Regular Expressions, Grammar generation and Parsers?? I would like to use tools like Yacc/Flex/Bison - but the problems i am facing are - How to use these tools? ...
Use somebody else's C parser. For example, the parser used by the clang project. http://clang.llvm.org/ Then you can focus on the other hard part of your problem: detecting errors.
5,367,900
5,532,027
C++ socket's send() causes system error 10053
I'm trying to send a message from my client to my server (currently they are both running in the same process, but I don't think it matters). The connection is established well (I can see it with "CurrPorts" - much more user friendly than TcpView). But then, when I send the message, I get the error: "An established co...
I'm so stupid... :/ I have this class MySocket which I create during Accept, but in its destructor, I CLOSE the socekt. thanks everybody :)
5,367,987
5,368,024
updating list in qt creator
hi every one i am working on qt creator. i have a list which is loaded with values store in a file when i run the program. but my problem is that the file is updating continuously after 30 sec so i want to refresh my list again with new values after 30 sec. how can i do that as sleep function is not working i want tha...
example: QTimer *reloadTimer = new QTimer(this); connect(reloadTimer, SIGNAL(timeout()), this, SLOT(reloadTheList())); reloadTimer->start(30000); given a member function this.reloadTheList(), this code (eg. when run in constructor) tells the QTimer to emit timeout() every 30 seconds (30k miliseconds), which you connec...
5,368,035
5,369,867
What's the meaning of bits in '/usr/include/c++/4.4/bits/'
What's the meaning of bits in '/usr/include/c++/4.4/bits/' Linux, gcc of course.
The official designation of that folder according to the libstdc++ documentation is: "Files included by standard headers and by other files in the bits directory" Where "bits" probably just means something trivial as "the bits that make up the implementation of what you include via the standard headers". For exam...
5,368,089
5,368,103
Overload output operator in a enum in C++
Its posible to overload the output operator inside an enum ? I'm getting all sort of errors(if I use class, I dont get any): ../src/oop.cpp:18:2: error: expected identifier before 'friend' ../src/oop.cpp:18:2: error: expected '}' before 'friend' ../src/oop.cpp:18:2: error: 'friend' used outside of class ...
enum MyEnum { foo, bar }; inline std::ostream & operator<<(std::ostream & Str, MyEnum V) { switch (V) { case foo: return Str << "foo"; case bar: return Str << "bar"; default: return Str << (int) V; }
5,368,093
5,368,111
Undefined symbol in shared library with g++
With JVMTI I am developing an agent to profile Java applications. Therefore a shared library libagent.so is compiled. Further I use the Qt framework: For now it consists only by these two source files: agent.cpp and agentserver.cpp However, when starting a Java application with my shared library libagent.so I get the e...
The error message is telling you that some element in AgentServer's vtable is undefined. The use of Q_OBJECT requires you to run moc on your source - and link to the qt libraries.
5,368,146
5,368,426
Templated "Listener" handler ambiguity problem
I'm using JUCE as a x-platform framework, and I'm using template listener classes to map button/combobox etc. callbacks to certain handler functions. Since the different widgets have their own callback function name, I use the following structure: template<typename Type, typename Widget> class ListenerBase : public Wid...
Edit Okay, after rethinking everything, the problem lies with ListenerBase<MyClass, Button> and ListenerBase<MyClass, Label> each defining an addHandler function, which because of inheritance doesn't seem to count as overloading, even though they have different signatures (one with a Button* parameter, the other with a...
5,368,147
5,368,160
C++ Function Problem
I have gone over this back and forth and keep getting this error: 'ReadDials' : function does not take 0 arguments, can I get at least a point in the right direction? #include <iostream> using namespace std; //declaring function int ReadDials(int); int main() { //declaring each character of the phone number ...
Actually ReadDials takes 9 arguments, so you can't call ReadDials() without passing anithing to it. then, as far as I can see, the function "karma" seems to return the number the user "dials", but it will probably fail in this intent, since parameters are passed by value, so the function changes are not propagate outsi...
5,368,258
5,368,273
The copy constructor and assignment operator
If I override operator= will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator= automatically 'inherit' the behavior from the copy constructor?
No, they are different operators. The copy constructor is for creating a new object. It copies an existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values ...
5,368,300
5,368,422
C++ Regular Expressions multiline replace
I seek more knowledge of ones mind again. I have a C++ solution which uses the Boost libraries as the solution requires to work within a Linux enviroment. However my knowledge is within C# and C++ is a somewhat new area of mine which I've dived into. I'm looking for an example use of how I could create a somewhat temp...
Actually, you don't need the power of regular expressions, you can do with find/replace. void replaceall(string& source, const string& pattern, const string& replacement) { int curr = 0; while ((curr = str.find(pattern, curr)) != string::npos) str.replace(curr, parrern.length(), replacement); } void su...
5,368,369
5,368,388
Binary shift of int not possible
usigned int val = 1; val <<= 30; cout << intToBin(val) << endl; string intToBin(unsigned int val) { unsigned int k=1; string ret; while (k <= val) { if (k & val) { ret.insert(0,"1"); } else { ret.insert(0,"0"); } k <<= 1; } return ret; } Thi...
Your while loop will not terminate if val is >= 2^31. This is because k == 2^31 is still <= val but 2^31 << 1 == 2^32 overflows and becomes 0. Which is still smaller than the limit. You could extend your condition to break if k == 0 too, then the problem should disappear. (^ means exponentiation not xor in this post)
5,368,497
5,368,512
STL syntax, container with reference to pointer
i want to create a container which contains references to pointers 1) Is this possible? 2) What is the syntax? I imagine its <T*&> ie: std::stack< int*& > stack_; but this just gives me errors "xmemory: pointer to reference is illegal."
You cannot use references as the element type of a container, because there is no such thing as a reference object in C++. What exactly are you trying to achieve? Why not simply use a std::stack<int>?
5,368,531
5,368,571
Why can't I create an array of size n?
Possible Duplicate: Why can't I create an array with size determined by a global variable? This is definition of simple array with constant size 4, which is stored in stack memory: int array[4]; Now If I want to declare array of dynamic size in stack it seems that I should write this code: int n; cin >> n; int arra...
int n; cin >> n; int array[n]; This will work if use g++. g++ support VLAs as an extension. However ISO C++ mandates size of an array to be a constant expression i.e the size must be known at compile time. Why is it that C++ don't allow you to create array of dynamic length in stack memory? Simple answer "Because th...
5,368,560
5,368,607
String Variable Argument Lists in C++
I'm trying to use a variable argument list to make NPCs in my text-based RPG talk easily. There's so many errors I'm not even bothering to post them - I gather I'm using this so wrong you won't need the output. If you do, of course I'll post it. Here's the two files you'll need: //Globals.h #ifndef _GLOBALS_ #define _...
How about a vector of strings? #include <vector> #include <string> void NPCTalk(std::string const& speaker, std::vector<std::string> const& text) { for (std::vector<std::string>::const_iterator it = text.begin(); it != text.end(); ++it) { std::cout << s...
5,368,862
5,368,930
Why do multiple-inherited functions with same name but different signatures not get treated as overloaded functions?
The following snippet produces an "ambigious call to foo" error during compilation, and I'd like to know if there is any way around this problem without fully qualifying the call to foo: #include <iostream> struct Base1{ void foo(int){ } }; struct Base2{ void foo(float){ } }; struct Derived : public ...
Member lookup rules are defined in Section 10.2/2 The following steps define the result of name lookup in a class scope, C. First, every declaration for the name in the class and in each of its base class sub-objects is considered. A member name f in one sub-object B hides a member name f in a sub-object A if A is a...
5,368,867
5,368,972
Persistent pointer to parent
How can I use this as a persistent pointer, so it would work outside of the current scope? As for this example, I don't know how should I set the fx.parent: class Effect { Card* parent; }; class Card { vector<Effect> effects; void addEffect(Effect); }; Card::addEffect(Effect fx) { /* * the `this`...
Pushing elements into containers copies them. So you should link the copy, not the original: Card::addEffect(Effect fx) { effects.push_back(fx); effects.back().parent = this; } Otherwise, you will link to a local variable that goes out of scope when addEffect returns. Note that this code generates another copy...
5,368,891
5,368,900
Calculate number of bit shifting in 30 bit integers that gives a maximum value
I am preparing for a programming interview. So, I tried to solve some of the outdated interview questions just to get prepared for the coming interview. I was stuck in solving the following question: A cyclic right shift of 30-bit unsigned integer X is a number obtained from shifting all bits of a binary representation...
What is the best way to solve this problem? m = (n << i) & 0x3fffffff;
5,368,988
5,369,017
new or new[] operator
Consider following code: typedef SomeType type_t[2]; SomeType * arr1 = new type_t; //new or new[] ??? type_t * arr2 = new type_t[3]; //new or new[] ??? According standard which version of new will be called in 1-st and 2-nd cases ( new or new[]) and how to delete arr1 and arr2 (with delete or delete[]) ?
First case allocates a one-dimensional array, second case a two-dimensional array. Both of them must be released via delete[], otherwise you will get undefined behavior.
5,369,135
5,369,431
Export functions which returns a reference
I want to export into python module (written in c++, with boost.python library) such function: Vec2<Type> &normalize () Type dot(const Vec2<Type> &vector) const These are the members of template class Vec2. Here is my export code: bp::class_< Vec2<int> >("Vec2i", bp::init<int, int>()) .def("Length", &Vec2<int>::l...
If you look at vec2.h (or the docs you link to), you'll see that dot and normalize are both overloaded, since there also exist static versions of these. You can get around this by using a few function pointers: Vec2<int> &(Vec2<int>::*norm)() = &Vec2<int>::normalize; and then using that in the def, as explained here.
5,369,196
5,369,221
Polymorphic classes in templates
Let's say we have a class hierarchy where we have a generic Animal class, which has several classes directly inherit from it (such as Dog, Cat, Horse, etc..). When using templates on this inheritance hierarchy, is it legal to just use SomeTemplateClass<Animal> and then shove in Dogs and Cats and Horses into this templa...
Answer of your question if No. But you can use SomeTemplateClass<Animal*> and pass pointers of objects of derived classes to it. For example, if you have a templated Stack class, where you want to host all sorts of animals. You can simply do following: Stack<Animal*> s; Dog d; s.push(&d); Cat c; s.push(&c)
5,369,265
5,369,297
Declaration is incompatible with prototype
I'm confused at to why I'm getting this error. The title's error is happening with the prototype in Globals.h: void NPCTalk(std::string const& speaker,std::vector<std::string> const& text) and the function in Functions.cpp: void NPCTalk(string const& speaker,std::vector<std::string> const& text){ vector<string>::c...
You forgot the semicolon at the end of the prototype. Your signatures are a match which suggests to me that you may well have forgotten the namespace in question.
5,369,300
5,372,144
How can I add a checkbox/radio button to QTableWidget
How can I add a checkbox/radiobutton/combobox to a QTableWidget or a QListWidget?
For a checkbox using the item's setCheckState method should do what you need both for list and table widgets. See if code below would work for you: List widget: QListWidgetItem *item0 = new QListWidgetItem(tr("First"), listWidget); QListWidgetItem *item1 = new QListWidgetItem(tr("Second"), listWidget); item0->setCheck...
5,369,536
5,369,570
Queue implementation with heap
I'm trying to implement a queue. This is my framework class Queue { HANDLE heap; Int *buf; Int head, tail; Int spaceAllocated; Int sizeQ; public: void Push (Int item); Int Pop (Int *array, int batchSize); } I'm doing this with a heap using windows API. What is the purpose of the buff...
*Buf is the actual memory pointer you'll use to store your items. I imagine you're using VirtualAlloc() here to create your buffer? If so, you need to know the maximum size of your queue. As an aside, why can you not use the STL queue?
5,369,632
5,369,705
Drawing stroked text with True Type Fonts
Right now in my game I'm drawing true type fonts like this: for(int i = linesSkipped; i <= maxitems + linesSkipped; ++i) { if(i >= (int)textRows.size()) { break; } paintargs.graphics()->drawText(AguiPoint(textX - 2, textY - 2 + (i * getFont().getLineHeight()))...
You need to draw the text in all corners! What you're doing is drawing in the top-left corner and in the bottom-right corner, which is respectively X=-2, Y=-2 and X=2, Y=2. What you need to do, is to draw them in the bottom-left and the top-right corner too, which would be respectively X=-2, Y=2 and X=2, Y=-2.
5,369,770
5,369,783
bool to int conversion
How portable is this conversion. Can I be sure that both assertions pass? int x = 4<5; assert(x==1); x = 4>5; assert(x==0); Don't ask why. I know that it is ugly. Thank you.
int x = 4<5; Completely portable. Standard conformant. bool to int conversion is implicit! §4.7/4 from the C++ 11 or 14 Standard, §7.8/4 from the C++ 17 Standard, §7.3.9/2 from the 20 Standard says (Integral Conversion) If the source type is bool, the value false is converted to zero and the value true is converted t...
5,369,790
5,370,906
changing llvm::Function signature after code generation, before last CreateRet
I'm trying to implement the following functionality; a function with no explicit return will by default return the last evaluation in the last executed block So, currently the process i'm doing is 1) create a Function llvm::Function* result = llvm::Function::Create(Compiler::Detail::getAnonymousFunctionSignature(llv...
You cannot change function signature, because this will mean that it will have different Type (and thus you will need to update all the users, etc.; this procedure in most cases cannot be done automagically). There are multiple possible solutions, for example, you can create the function with the updated signature, the...
5,369,919
5,369,934
how do i implement the bisection method using this function prototype in C++
double p1::root(double (*pf)(double k), int a, int b, double e) im not sure how to go about it, i understand that i have to loop that pinpoints the midpoint and such double p1::root(double (*pf)(double k), int a, int b, double e) { // void nrerror(char error_text[]); in...
Maybe Numerical Recipes will give you an idea. Hint: it's recursive.
5,370,003
5,370,040
How do I serialize telnet like communication on a bidirectional socket connection?
I have implemented TCP/IP communication between a VB and VC++ programs running on the same machine. On the VC++ side I spawn a thread which listens for connections. On the VB side I use the Winsock API to connect to the C++ server. Everything seems to work fine, especially when I manually debug and step through the com...
Rather than packet collision, my guess would be that you're reading more than you expect from the socket. Could it be that your last read from the socket looks something like OTHER STUFF\nDATA REC and on the next read you get "EIVED"?
5,370,092
5,370,122
how do I declare an integer variable of 1024 bits in length?
I'm trying to write an algorithm for a number theory/computer science merged class that can factor large numbers in better than exponential time. I am using the g++ compiler on a 64 bit machine but when I chain together long it will only allow me to do up to 2 longs. Is there any way to tell it to use an arbitrary amou...
You'll need a library. A good one is http://gmplib.org/
5,370,171
5,370,243
C++: How to build an events / messaging system without void pointers?
I'd like to have a dynamic messaging system in my C++ project, one where there is a fixed list of existing events, events can be triggered anywhere during runtime, and where you can subscribe callback functions to certain events. There should be an option for arguments passed around in those events. For example, one ev...
You could use a base class, optionally abstract, and use dynamic_cast. The argument will be checked at run-time. A compile-time would probably be better, though. class EventArgs { public: virtual ~EventArgs(); }; class PlayerChatEventArgs : public EventArgs { public: PlayerChatEventArgs(Player* player, const std...
5,370,180
5,370,960
Eclipse CDT build/run on file basis
In my scenario I have a C++ project in CDT Eclipse. This projects however is rather a collection of individual (helper) programs than one complex application. Consequently I want to be able to build and run them individually. My project structure is very simple and looks like: src/app1.cpp src/app2.cpp src/... Note t...
The straightforward way to succeed what you aim is to create a Makefile project with CDT and add a new target rule for each of your applications inside your Makefile. You can even use SCons or other build systems with a CDT Makefile project and obtain the same effect. You can also trick the managed build to create exec...
5,370,201
5,370,219
Do C++ mangled names stay consistent when compiled on different computers?
In general, what I've observed using nm on Linux is that T symbol names (which I'm interested in) stay consistent across different computers even when I'm not using extern "C". Is my observation correct? Note I'm using gcc on all computers.
It would be very unusual for the computer, the time of day, or the weather to affect name mangling. What's more likely to cause deviations is differences in compiler version. But many linux platforms define an ABI (application binary interface) for C++ which includes, among other things, the name mangling rules. On th...
5,370,283
5,370,333
Binary tree where value of each node holds the sum of child nodes
This question was asked of me in an interview. How can we convert a BT such that every node in it has a value which is the sum of its child nodes?
Here is a solution that can help you: (the link explains it with tree-diagrams) Convert an arbitrary Binary Tree to a tree that holds Children Sum Property /* This function changes a tree to to hold children sum property */ void convertTree(struct node* node) { int left_data = 0, right_data = 0, diff; /* If tr...
5,370,377
5,370,401
Compile error when calling managed C++ from C#
I am new to .net . I have a managed C++ library. It looks like this. // header file namespace cppnetdll { public __gc class Class1 { public: static int foo_int(void); }; } // source file namespace cppnetdll { int Class1::foo_int(void) { return 123; } } I can call this from a managed c++ program. When I try to call it...
You do not use a [DllImport] directive to call code that's written in managed C++. That is only intended for native DLLs that export their functions. Neither of which applies to yours, it isn't native and you don't export the function. You built a managed assembly, you can treat it just like one you'd have written in...
5,370,388
5,370,446
defining operator + , = and +=
I once read the following statement from a C++ notes, In C++, defining operator + and = does not give the right meaning to +=. This language-design bug is fixed in C# I would like to know what exactly does this statement want to say? Is that related to operator overload?
I prefer C++ operator overloading mechanism. It definitely not a design bug according to me. +, = and += are three different operators. If you want to use += you need to overload +=. Overloading + and = won't make += work. I would like to add that in E1 += E2 E1 gets evaluated only once as far as C++ is concerned. I do...
5,370,413
5,370,476
Multiple Defined Symbols C++ error
I thought ifndef something #define something body #endif solved this error, so I'm not sure why this is happening. //Library.h #ifndef __LIBRARY__ #define __LIBRARY__ #include <iostream> #include <string> #include <cstring> #include <cmath> #include <cstdio> #include <cstdarg> #include <vector> #include <ctime> #inclu...
The problem is that in your globals.h header file, you're declaring a suite of variables that by default have external linkage: namely, all the globals! When you prototype a function in a header file, you are declaring a function, but not defining it. It's perfectly legal to have multiple declarations of the same func...
5,370,435
5,370,499
Strange behaviour of memory mapped file, some observations and some questions
Please look at this code below. #include <windows.h> void Write(char *pBuffer) { // pBuffer -= 4*sizeof(int); for(int i = 0; i<20; i++) *(pBuffer + sizeof(int)*i) = i+1; } void main() { HANDLE hFile = ::CreateFile("file", GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL...
The virtual memory manager has to map memory by the page, so the extent will in effect be rounded up to the nearest 4kB (or whatever your system page size is). I don't think it's documented whether writes into the same page as mapped data, but beyond the end of the mapping, will be committed back to the file. So don't...
5,370,497
5,371,224
memory safety for encrypted, sensitive data
im writing a server in c++ that will handle safe connections where sensitive data will be sent. the goal is never saving the data in unencrypted form anywhere outside memory, and keeping it at a defined space in the memory (to be overwritten after its no longer needed) will allocating a large chunk of memory and using ...
From the manual of a tool that handles passwords: It's also debatable whether mlock() is a proper way to protect sensitive information. According to POSIX, mlock()-ing a page guarantees that it is in memory (useful for realtime applications), not that it isn't in the swap (useful for security applications). Po...
5,370,513
5,370,578
Segmentation fault when calling virtual method
Here is my code, I casted the buffer to different type of objects, is this what causes the failure? I really want to know why the FromBase::find2(int key) works, but not FromBase::find(int key)? class Base { public: virtual int find(int key)=0; int keys[4]; }; class FromBase:public Base { public: ...
There is a high chance that you are overwriting the virtual function table with your code leading to a bad address when you call the method. You cannot just save objects into a file and expect to restore them by just restoring the memory content at the time they were saved. There are some nice libraries like boost::ser...
5,370,554
5,370,623
What is the most concise yet accurate way to describe what a virtual function is in C++?
Being asked to describe what a virtual function is seems to be one of the most common questions in interviews assessing basic C++ knowledge. However, after several years programming C++, I still have the uncomfortable feeling that I don't really understand how best to define what they are. If I consult wikipedia, I see...
I've always thought that this quote captures the essence of virtual functions: A virtual function is a way of defining a family of related behaviors that can be customized by the entities that actual have to do those behaviors. If you ignore all the C++-isms of virtual functions - how having virtual functions enables...
5,370,628
5,370,649
is there a way to declare a group of members with the same accessor in c#?
i have this basic question : is there a way to declare a group of members with the same accessor in c#?, something like "accessor:" of c++ that specify that from that line downward every member have this accessor Edit: with "accessor" i mean access-specifier like public, private, protected, etc.
I think you meant access-specifiers. If so, then no. You cannot do that in C#, like you do in C++. However, if it's private, then you can omit it altogether, because by default, everything (fields, properties, methods) in C# is private.
5,370,737
5,370,779
Is there a potential for resource leak/double free here?
The following sample (not compiled so I won't vouch for syntax) pulls two resources from resource pools (not allocated with new), then "binds" them together with MyClass for the duration of a certain transaction. The transaction, implemented here by myFunc, attempts to protect against leakage of these resources by trac...
I don't see any leak in this small code. If the constructor throws exception, then the destructor would not be called, since the object never existed. Hence I don't see double-delete either! From this article by Herb Sutter :Constructor Exceptions in C++, C#, and Java: constructor conceptually turns a suitably sized c...
5,370,804
5,373,515
How to work out width and height of multined string with font?
My program draws text strings into rectangles by working out the width and height of the text, and selecting a smaller font if its too big for the rectangle. But originally i only used single lined text, now i need some multi lined, i used to use GetTextExtentPoint32 but if theres \n in the string, it seems to think of...
Docs for DrawText state that while it only returns the height, it modifies the rectangle you pass it. Are you checking the rectangle, or only the return value? It sounds like you would actually want to pass in a rectangle with a large width (ie. maximum width you want to allow), and DrawText will reduce as necessary. (...
5,371,081
5,371,179
Provide a std::istream interface to an existing buffer without copying it
I have a buffer of chars of a fixed length and I'd like to feed it to a function that takes a std::istream&. How can I do that without copying the buffer? If it means deriving a custom streambuf, I think I'll live with the copy. I'm just wondering if I'm missing something straightforward. Here's what I'm doing now (whi...
I've been in a similar situation myself, and instead of creating everything myself I used Boost.Iostreams, creating a read-only source device. Untested, but this may work: class ConstBufferDevice { public: typedef char char_type; struct category : virtual boost::iostreams::device_tag, virtual boost::...
5,371,166
5,371,522
Visual studio not allowing ommision of default parameters?
I am using VS2010 on a C++ project using opencv. Many of the calls in opencv have default parameters for the last few parameters to functions. However, when omitting these parameters in function calls, Visual Studio complains and says "functionname: too few arguments for call Is this a quirk of visual studio? Is it ...
The declaration for cvInitMatHeader() is this: CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, int type, void* data CV_DEFAULT(NULL), int step CV_DEFAULT(CV_AUTOSTEP) ); The definition of CV_DEFAULT looks something like this: #ifdef __cplusplus #define CV_DEFAULT(val) = val #else #define CV...
5,371,499
5,371,524
C++ friend class data access
C++ newbie here. I am a science guy writing a cfd (ish) code. I have created a class for all solving functions, and one that handles operations on a grid. The grid class wants to be able to see a few of the variables stored in the solving class, as passing them all to the grid class seems like a bit of effort. So in my...
a1 only exists as a part of instances of class A. In other words, you need an A object in order to access a1. EDIT: but it turns out that wasn't the only problem in the source you gave. This works: #include <iostream> using namespace std; class B; class A { friend class B; private: int a1; public: void ...
5,371,790
5,371,905
Creating A Better Hash Function
#include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; class Item { public: Item(const string & v): value(v), next(0) { } string value; Item * next; }; int hash_function(const string & s) { unsigned int hashval = 0; int i = s.length(); while (i > 0) { ...
Instead of blindly adding each letter, give some weight to each, so that cpp, pcp, ppc all could produce different hashvalue. Here is little improved version: int hash_function(const string & s) { double hashval = 0; int i = s.length(); double weight = 1.0; while (i > 0) { hashval += weight...
5,371,900
5,371,951
Class declaration without static
I have a class Queue; I have these variables defined in that class... int head, tail; One of the functions check if (head==tail), however I cannot declare head and tail to be equal to 0 in that function or else every time i call that function it will reset itself... How can i declare head and tail to be equal to 0 with...
You can do that in the constructor; more specifically in the initialization-list of the constructor! class Queue { int head, tail; public: Queue() : head(0), tail(0) {} // ^^^^^^^^^^^^^^^^ this is called initialization-list! }; In the initializatin-list you can initialize all your variables! If that ...
5,372,006
5,383,885
how to specify path to usr/lib of a specific machine in makefile?
I am using some libraries installed at my local machine in directory /usr/lib/. I want to run my program on another machine where the same libraries are installed but other version. How can I specify the path that the program runs on another machine but the libraries are used from my computer ? Thanks
Secure shell does not provide a service for finding binaries and libraries on the originating machine and running them on the remote machine (or indeed the other way 'round). You will need to deploy the executable. I'd suggest: Compile on you home machine, linking the desired libraries statically. The static link is c...
5,372,049
5,372,057
How to automatically open an input file in C++?
In my program written in C++, I open a file as follows: std::ifstream file("testfile.txt"); This usage can handle the scenario where the input file has a fixed name of "testfile.txt". I would like to know how to allow the user to input a file name, e.g., "userA.txt", and the program automatically opens this file, "use...
Use a variable. I suggest finding a good introductory book if you're not clear on what they are yet. #include <iostream> #include <string> // ... std::string filename; // This is a variable of type std::string which holds a series of characters in memory std::cin >> filename; // Read in the filename from the c...
5,372,070
5,372,221
Protected/Private Inheritance Casting
I came across this issue accidentally when I was going over inheritance and up/down casting. Why is this not allowed (code is commented to show sections that are not allowed)? Now I can guess as to why it is not allowed but a factual answer would be great. As for the code that is allowed, I know it is because (Base*) i...
Sounds like you are correct. One thing to remember is that traditional OO principles such as the LSP only describe public inheritance. Non-public inheritance falls in-between inheritance and composition, the base subobject is non-public like composition, but you can also take advantage of features which rely on inheri...
5,372,084
5,372,200
Weird error in binary search tree
#include <iostream> using namespace std; #define YES 1 #define NO 0 class tree { private: public: struct leaf { int data; leaf *l; leaf *r; }; struct leaf *p; tree(); ~tree(); void destruct(leaf *q); tree(tree&...
I believe the error is that you have no terminating condition for your recursion. Consider the case where len == 0, you will execute this line of code: bst->l = createBST(preOrder + 1, inOrder, i); This will pass in a length of 0 and the same thing will happen again. This is infinite recursion, and will cause a segm...
5,372,091
5,372,137
Are static member functions in c++ copied in multiple translation units?
I have a helper class in my program which has many static functions used in different classes of my program. E.g. helper.h: Class helper { public: static void fn1 () { /* defined in header itself */ } /* fn2 defined in src file helper.cpp */ static void fn2(); } Helper has only static member function...
Functions defined inside the class body are implicitly marked inline. If you take the address of the function, the compiler will also create a regular copy of the function (per compilation unit), but the linker will pick just one of these copies to include in the executable, so there's only one address. However, the i...
5,372,147
5,372,623
When loading an OBJ i get this
and this time i have loaded a model successfully! yay!! but theres a slight problem, one that i had with another obj loader... heres what it looks like: http://img132.imageshack.us/i/newglitch2.jpg/ heres another angle if u cant see it right away: http://img42.imageshack.us/i/newglitch3.jpg/ now this is supposed to loo...
gluPerspective(50.f,(double)800 / (double)600,0.f,200.f); ^^^ | That's your problem right there ---------------+ The near clip distance must be greater than 0 for perspective projections. Actually you should choose near to b...
5,372,153
5,372,181
Assembly language output in a C++ compiler
Does a C++ compiler generate machine code via assembly language code (i.e., c++ compiler first converts C++ code to assembly language code and then uses assembly language compiler to convert it to machine code), or is assembly language output generation just an option for reference or debugging purposes?
It doesn't have to, but most do it anyway, as the same assembler (program) can be used for the output of the C/C++/whatever-to-assembler compiler. g++ for example generates assembler code first (you can see the generated assembler using the -S switch). MSVC does it too (/FAs).
5,372,344
5,372,378
How do I properly modify a .def file in a Visual C++ 6 program?
I'm doing maintenance on a C++ 6.0 project that uses a .def file to handle function exports. I had to add a pair of instance methods to a class definition, but I don't know how to add these methods to the .def file so they get exported. Each line under the EXPORTS section in the .def file looks something like ?MethodNa...
You are exporting the C++ mangled symbols. I would add a __declspec(dllexport) in front of them temporarily and then load the DLL in something like Dependency Walker, or use dumpbin to see what is exported. This will give you the mangled symbol for you new functions and then you can add that to the .def file and remo...
5,372,532
5,372,628
Writing part of a compiler (written in c++) in Perl
i am trying to learn more about compilers and programming languages, unfortunately my university doesnt offer a course about compilers and so i have to do myself (thank you internet). At the moment im tryin to understand and to implement a lexer for my language and i need regular expressions. I am used to script perl r...
No reason you can't, part of being a good programmer is using the right tool for the job, and perl is VERY good at text processing. However, instead of thinking about stuffing a perl-based lexer into your C++ compiler (written in C++, not compiling C++, I hope), you should think about writing a perl module in C++, and ...
5,372,565
5,372,810
Runtime error (dll loading) with win32 applications on x64 system, while compiling 0K
I originally designed a win32 application on win7 32bits, with VC9.0. I recently upgraded to win7 64 bits, and tried to build+execute the previous application. Building runs fine (win32 application), but on runtime I get the error "[...] has exited with code -1073741701 (0xc000007b)." I guess this results of the loadin...
It appears you are loading a 64-bit DLL into a 32-bit process or vice versa. Here's how I would go about tracking down the offending DLL. The first step is to run dumpbin.exe (use a VS command prompt to get it on the PATH) on the executable to ensure the architecture is what you expect: dumpbin.exe /headers foo.exe. ...
5,372,588
5,372,715
writing chess engine for arena gui
I'm interested in implementing a chess engine for arena GUI http://www.playwitharena.com. Do you know some sort of information regarding the specific guidelines that you must follow in order to make the engine usable in Arena (ie so that you can actually import the engine from Arena). Also do you think it's possible to...
You can write your engine in any language and have it work with Arena, provided it speaks the WinBoard or UCI protocol. Both of these involve having your engine (which runs as a separate process) input and output plain text. You can write it in C++, Java, Visual Basic, COBOL, Forth, or whatever else you fancy. (Note: I...
5,372,591
5,372,636
Why is the return value of malloc(0) implementation-defined?
ISO/IEC 9899:TC2 (i.e. the C99 standard), §7.20.3 states: If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object. In oth...
The C99 Rationale (PDF link) discusses the memory management functions (from C99 7.20.3) and explains: The treatment of null pointers and zero-length allocation requests in the definition of these functions was in part guided by a desire to support this paradigm: OBJ * p; // pointer to a variable list of OBJs /* ...
5,372,640
5,372,671
c++ pointer to a reference
Is it legal to have a pointer of a reference in C++? For example: int &ref = array[idx]; func(&ref); One reason I can think of why you might want to do this if func() already exists in a library which you can't change.
That code is legal, but it does not create a pointer to the reference. It creates a pointer to the referent (the reference target).
5,372,656
5,372,675
What are the rules for virtual function lookup?
#include <iostream> class base { public: virtual void print (int a) { std::cout << "a: " << a << " base\n"; } virtual void print (int a, int b) { std::cout << "base\n"; } }; class derived : public base { public: virtual void print (double d) { ...
derived::print does not override any member function in base. It is declared as having a single parameter of type double but the two virtual member functions named print in base are declared as having one and two parameters of type int. When you use b->print(d), only member functions in base are considered during over...
5,372,707
5,372,762
in C++, what's the difference between an object and a pointer to an object?
In java and objective-c, a variable representing an object is generally a pointer to that object. However, it seems that in C++, it's common to have non-pointer types hold objects. What's the difference between the two? If I pass a struct as an argument to a function, I believe I'm passing by value, meaning I'm actual...
It's exactly as you said. When you pass an object by value, its copy constructor is invoked to produce a new instance of such object that will be used inside the function. The changes done to such new object won't be reflected to the original one1. As with structures, the default copy constructor just does a shallow co...
5,372,755
5,372,801
What is an operating system independent way to open file with associated program from C++?
What is an operating system independent way to open a file with associated program from C++? Is there a solution in Boost, or something like it? More specifically, something that would cover Windows, Mac OS X, and Linux. What I am trying to do is open a file ending in the .txt extension in the program that the user alr...
QDesktopServices::openUrl from Qt library provides this. It is asynchronous (non-blocking).
5,372,865
5,372,907
C++: structs across classes
I have two classes: MazeClass and CreatureClass, that use a struct called "coordinates," how am I able to use the struct across both classes? I've tried to put the struct in twice and I get: MazeClass.h:16:8: error: redefinition of ‘struct coordinate’ CreatureClass.h:11:18: error: previous definition of ‘struct coordi...
You can declare the struct in one of the classes in public. Choose the class that is more relevant: class MazeClass { public: struct coordinate {} ; } ; Other classes can access this type as MazeClass::coordinate. Alternatively you can bring it with a typedef. class CreatureClass { public: typedef MazeClass::c...
5,373,107
5,373,143
How to implement static class member functions in *.cpp file?
Is it possible to implement static class member functions in *.cpp file instead of doing it in the header file ? Are all static functions always inline?
It is. The key is to use the static keyword only in the header file, not in the source file! test.hpp: class A { public: static int a(int i); // use `static` here }; test.cpp: #include <iostream> #include "test.hpp" int A::a(int i) { // do **not** use `static` here! return i + 2; } using namespace std; in...
5,373,159
5,373,175
How do I use the switch statement?
I am trying to understand the switch statement better. I don't need the code but kinda a walkthrough on how it would be done. If someone enters a 7 digit phone number EG. 555-3333 but enters it as "jkl-deff" as it would correspodnd to the letters on the dial pad, how would I change the output back to numbers? Would thi...
To do that with a switch statement, you'd have to walk through the char array, switching on each character. Group all the chars that have the same number together. Something like switch (phoneChar[i]) case 'a': case 'b': case 'c': newChar[i] = '2'; break; That said, I'm not sure that switch case is the best wa...
5,373,171
5,373,191
Readability a=b=c or a=c; b=c;?
I have a class which has a group of integers, say foo() { int a; int b; int c; int d; .... string s; } Now the question is for the best readbility, the init() function for foo(), should it look like void init() { a=b=c=d=1; //for some reason they are init to 1; s = "abc"; } or void init() { a=1; b...
My personal preference is a=b=c=d for the following reasons: It is concise, saves lines It conveys the concept that (a/b/c/d) are initialized to the same thing, that they are related However, caveat: Don't do that if a/b/c/d are not related (and just happens to be initialized to 1). You'll reduce the readability of...
5,373,226
5,374,353
Trouble overloading operator >> for a matrix class
I am trying to learn operator overloading by working on overloading >> for a matrix class to enable the key-board based input for a matrix by calling sth such as Matrix M1; cin >> M1; The operator overloading part is given in the following istream &operator>>(istream &in, Matrix &m) { for (int i = 0; i < m.dx; +...
I don't think your code is wrong particularly. If pressed I would suggest checking the stream condition in the loop. For your information, the following code worked when I tested: struct Matrix { static int const dx = 2, dy = 2; int p[ dx ][ dy ]; }; istream &operator>>(istream &in, Matrix &m) { for (int i...
5,373,307
5,373,317
How to handle Unix pipe
How do I get the filename from redirection from the shell in my C++ code? i.e. ./MyProgram < myfile , I want to get myfile as the filename and its content line by line. **Edit: I managed to get the input from file. Thanks for the help. However, after the looping through the file content, I want to keep user input with ...
You can't (at least not portably). This information is not provided to the program. Instead, you can access the data from myfile (in your example) by reading from standard input. E.g., you can use C++'s getline with cin as the first parameter.
5,373,560
5,373,565
invalid pure specifier (only `= 0' is allowed) before ‘;’ token error with g++
I have this C++ code. #include <string> #define IC(E) virtual const E const = NULL; struct IDumpable { IC(std::string ToDumpString()); }; class Hello : public IDumpable { public: const std::string ToDumpString() const { std::string a("hello"); return a; } }; int main() { Hello hello; hel...
GCC uses a built-in __null for NULL (which is a constant integer expression evaluating to zero. __null on GCC satisfies such), so that it can detect special cases and warn about them. Like, accidentally passing NULL to a bool parameter, when it was intended to be passed to a pointer parameter (changes made to a functio...
5,373,766
5,373,835
adding a newline to file in C++
Can any body help me with this simple thing in file handling? The following is my code: #include<iostream> #include<fstream> using namespace std; int main() { ofstream savefile("anish.txt"); savefile<<"hi this is first program i writer" <<"\n this is an experiment"; savefile.close(); return 0 ; } It is running ...
First, you need to open the stream to write to a file: ofstream file; // out file stream file.open("anish.txt"); After that, you can write to the file using the << operator: file << "hi this is first program i writer"; Also, use std::endl instead of \n: file << "hi this is first program i writer" << endl << "this is ...
5,373,839
5,373,853
Best practice for the placement of inline functions in C++
Which is better for short functions (e.g. getters and setters) In the class definition header file At the end of the header file In the source file (in this case should I use the inline keyword or extern inline?)
You can't put inline functions in the source file (and have them used as inline) because their definition won't be available at the points the compiler needs them to inline the code. Between the other two options, I tend to put one liners into the class definition and any others at the end of the header.
5,373,846
5,373,859
Check if std::wstring is null or empty
How to check if an std::wstring is null or empty?
wstring is not a pointer, it cannot be null. You can check if it's empty (that is, is equivalent to "") either by direct comparison to the previous, or by: str.empty(); // == (str.size() == 0)
5,373,919
5,373,962
Windows winsock networking code: What am I missing?
I saw something that was a red flag for me when I ran this: nc -l -u -p 1500 This netcat command makes it listen for packets from UDP port 1500. Once i ran this on the windows command line, I immediately got a Windows Firewall has disabled features blah blah blah popup message. Sadly I realized that my own UDP code d...
You are binding to localhost, Windows firewall has separate configurations for Private, Public, and Domain, which presumably map onto intranet & localhost, the Internet, and Kerberos authenticated domain. Bind to 0.0.0.0 (INADDR_ANY) to listen on all interfaces.
5,374,042
5,374,236
Win32 GUI and callback to C++ function
So, basically I'm using a code like this one. It's a little simple window where you can only change text inside of an edit box and press a button that will make a callback to a function (DoSomethingCallback(text)). #include <windows.h> #define ID_EDIT 1 #define ID_BUTTON 2 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg...
I would go for calling QueueUserWorkItem() to handle it. If your DoSomethingCallback() is too long, there is no way to make your window responsive while DoSomethingCallback() is working since there is only one thread to run the code. Good Luck!
5,374,075
5,374,098
Why does inserting URLs in C and C++ code work?
Why does the following code compile? Which section of the language allows URLs to be added in C and C++ code? int main() { http://www.stackoverflow.com return 0; } Thanks in advance, Castro.
If you compiled with warnings, you would notice: warning: label ‘http’ defined but not used That should be indicative enough of the problem here. The http: text is treated as a label. Followed by // negating the remaining text as a comment, ignoring it. http://www.stackoverflow.com Even the SO syntax colour schemes i...
5,374,319
5,374,363
assignment operation confusion
What is the output of the following code: int main() { int k = (k = 2) + (k = 3) + (k = 5); printf("%d", k); } It does not give any error, why? I think it should give error because the assignment operations are on the same line as the definition of k. What I mean is int i = i; cannot compile. But it compiles. Why...
int i = i compiles because 3.3.1/1 (C++03) says The point of declaration for a name is immediately after its complete declarator and before its initializer So i is initialized with its own indeterminate value. However the code invokes Undefined Behaviour because k is being modified more than once between two sequenc...
5,374,326
5,374,439
Making sure the method declaration is inherited
How can I protect from accidental definition of non-inherited method where inherited definition is intended. I am told there is trick to express it, but nobody can recall it. Explanation. I have tree of classes: 'Base' <- 'C' <- 'D', below. Base defines pure virtual function. The function gets redefined in C then in D...
For this exact purpose C++0x introduces the override member function decorator, as is already implemented in VC++ 2005 and later: http://msdn.microsoft.com/en-us/library/41w3sh1c.aspx Alternatively, VC++ permits the following (presumably compiler-specific): #include <iostream> class Base { public: virtual void Ver...
5,374,350
5,374,422
warning while passing a string in c function
I have a function that will pass a string and manipulate. in the function call i am passing the string as such like myfunc ("hello"); In the function definition i have myfunc (char *array) { xxxx }; The program is working fine, but it throws a warning "pointer targets in passing argument 1 of 'myfunc' differ in s...
Strings are actually arrays of constant characters. That is, the type of "hello" is const char[6]. What this means is you cannot modify it. However, due to a silly conversion in C++, the array (in string literal form) can be implicitly converted to a non-const pointer to the first element. This is misleading, and dange...
5,374,447
5,456,862
How to do queries on hdf5 time series
i store (non equidistant) time series as tables in hdf5 files using the H5TB API. The format is like this: time channel1 channel2 0.0 x x 1.0 x x 2.0 x x There are also insertions of "detail data" like this: time channel1 channel2 0.0 x x 1.0 x x 1.2 ...
I found another (obvious) solution finally by myself. The easiest way is to open the hdf5 file only read the time channel and create an in memory map before reading the data channels. This process could even be optimized by reading the time channel with a sparse hyperslab. When the indexes at a particular time are know...