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,330,793
5,330,904
shared_ptr - pass by value vs pass by reference
Suppose I have: typedef boost::shared_ptr<Event> EventPtr; On one thread, I am creating an Event and sending it off to get dispatched: Event* event = new Event(); EventPtr eventPtr(event); EventDispatcher::dispatch(eventPtr); //pseudocode The EventDispatcher receives an EventPtr and adds it to a queue that gets proc...
The EventDispatcher receives an EventPtr and adds it to a queue that gets processed in another thread...but what is an appropriate method signature for the dispatch method? Either suggestion is fine; passing by const reference will likely be more efficient, since it won't have to modify the pointer's reference count....
5,330,834
5,330,872
Is the C++ `free` function thread-safe?
That is, if my C++ application allocates memory in one thread using malloc, will free successfully de-allocate the memory, if called from another thread, or can I expect it to throw an exception? Both threads belong to the same process. I am using Visual Studio 2008. Thanks.
The current standard doesn't make any guarantees about threads. On most implementations, malloc and free may be called from different threads. Visual C++ heap code also serializes access to heaps, so you should be fine.
5,330,835
19,974,554
Why is std::type_info noncopyable? Am I allowed to store it somewhere?
The std::type_info class is non-copyable. This makes it hard to store it in an object for later use. What should I do?
There is a much better solution in C++11. A new copyable wrapper called std::type_index. You need to include header "typeindex" to use it.
5,331,002
5,333,016
Serializing a Pointer using MFC CArchive (with mfc100d.dll, CMemFile)
I am running into an issue serializing and deserializing pointer data in VS2010 VC++. Basically, the program was unable to serialize and deserialize a CObList * pointer data. The source code does the normal steps to handle the process: 1) MyObject was inherited from CObject; 2) We added DECLARE_SERIAL(MyObject) in th...
Pointers can't be serialized. There is no guarantee that the application reading the file will have access to the same area of memory the OS will put the data in the same place the application reading the file will be placed in the same place in memory One idea is to emulate pointers by using file offsets. Thus ...
5,331,010
5,331,158
logic constant and physical constness
Possible Duplicate: Physical constness of a class In C++, regarding an object, what's the difference between logical constness and physical constness?
These are not standard terms, but I think that "physically constant" would mean a constant object, and "logically constant" would mean a constant reference or pointer. In the first case, the object is declared constant, Object const object;, or is a literal constant such as 1 or "hello", and must never be modified; it ...
5,331,616
5,331,853
Visual studio 2010 and kernel level programming!
I have MS Visual Studio 2010 and I am planning to start kernel level & hardware driver programming.. Can i use MS Studio 2010 to do that? if, what exactly i need to add for that IDE? In another way... what i need to do if i want to compile the following code in MS visual studio 2010? and what kind of project should i c...
Use the compiler and build scripts from the DDK. You can use any IDE you like, as long as it can call the DDK build script. EDIT: BTW, your code should not define _X86_. The DDK build tool will define the right macros corresponding to the target version of Windows.
5,331,872
5,331,883
C++, Boost: how to emulate matrix container memory structure?
So we have a matrix A N*M and a vector B (of ints or floats) we want to calculate A*B. We want to emulate ways matrices/vectors are held in memory (so to show how differ access speeds depending on how you nest cycles, for example that ijk is slower than kji when you keep data one way and vice versa another way). Is it...
You can use Boost.MultiArray to set up multidimensional arrays (with convenient indexing) with different choices of storage layouts, such as row- and column-major.
5,331,933
5,331,971
Why wont my while statement work?
I think i am doing everything correctly.....but obviously i am missing something, my while statement doesn't seem to ever get entered. Please help.... #include <iostream> using namespace std; void swap(int *aPtr, int *bPtr) { int holder=0; holder=*aPtr; *aPtr=*bPtr; *bPtr=holder; } void instantiator(i...
The test in your while loop is *bPtr > 0, yet you set b to 0 in main (using if (b=0)) and then pass a pointer to it as bPtr. Try fixing the if statement in main and see if that changes the behavior.
5,332,235
5,332,286
Avoiding getting a substring?
I have a situation where I have a std::string, and I only need characters x to x + y, and I think it would speed it up quite a bit if I instead could somehow do (char*)&string[x], but the problem is all my functions expect a NULL terminated string. What can I do? Thanks
Nothing nice can be done. The only trick I can think of is temporarily setting s[x+y+1] to 0, pass &s[x], then restore the character. But you should resort to this ONLY if you are sure this will reasonably boost the performance and that boost is necessary
5,332,419
5,332,480
a class design problem
In the book of "The C++ programming language", author gave the following example. He mentioned that " the cache needs to be filled before it can be used". It seems to me that this is why the function of compute_cache_value is placed. But I do not understand what does the function of string_rep( ) do in accordance with ...
string_rep checks to see if there's a cached string representation of the date. If not, it calls the compute_cache_value method to create the string representation and cache it, and then marks the cache representation as valid so future calls to string_rep don't recalculate it. The line const Date d2; will display unde...
5,332,609
5,332,814
C and C++ static linking: just a copy?
When someone statically links a .lib, will the linker copy the whole contents of lib into the final executable or just the functions used in the object files?
The whole library? -- No. Just the functions you called? -- No. Something else? -- Yes. It certainly doesn't throw in the whole library. But it doesn't necessarily include just "the functions used in the object files" either. The linker will make a recursively built list of which object modules in the library satisf...
5,332,631
5,333,531
"Template typedef" inside a copy constructor doesn't work
Some background: I'm writing a policy-based smart pointer (like SmartPtr in the Loki library), which can have destructive copy semantics like auto_ptr. Therefore, it needs to have a template copy constructor taking non-const reference to modify the object being copied. What I'm trying to do is to parametrize the constn...
Perhaps something like this might work for you. I've used std::enable_if from C++0x. You could just as easily use boost's, or roll your own (it's only a couple lines of code). #include <type_traits> struct MyCopyPolicy { static const bool kIsCopyArgConst = true; }; template <typename T, class CopyPolicy> struct...
5,332,811
5,332,951
Why is my method going into infinite recursion?
I've written a method to help build a quadtree. Each quadtree has a root node, and a root node has 4 children. I'm using depth recursion to stop this function from dividing too many times. The depth that is passed in is equal to the log base 2 of the side of the square (a square is always passed in). However, I get inf...
If the n->isLeaf() condition means "all n's children are null", then I suppose it is always false here.
5,332,882
5,332,892
problem with `==` operator
There is some class wComplex with == operator. #ifndef WCOMPLEX_H #define WCOMPLEX_H #include <stdio.h> // sample class of complex-like numbers with weird `==` operator class wComplex{ private: double realPart; double imagePart; public: wComplex(); wComplex(double R); wComplex(double R, double I)...
You have a const reference to T in push() but your operator== only accepts non-const references. bool wComplex::operator==(wComplex &El) should be bool wComplex::operator==(wComplex const &El) const Or, optimally, your operator== should be a free function: bool operator==(wComplex const & Left, wComplex const & Right...
5,332,928
5,333,094
Cross-platform C++ Directory Managing
Are there any cross platform libraries that will help me place certain file in different directories. For example in windows a config file will probably go in app data, yet in Linux it will go in /etc/ or /use/etc/ depending on where it was installed. Is there any way to do this transparently?
boost::filesystem will should soon provide such functionalities (but not yet). I would be you, I'd use boost::filesystem and provide different addresses of user folders by platforms, then when boost::filesystem provide the feature, replace the implementations.
5,332,934
5,333,340
Optimizing WordWrap Algorithm
I have a word-wrap algorithm that basically generates lines of text that fit the width of the text. Unfortunately, it gets slow when I add too much text. I was wondering if I oversaw any major optimizations that could be made. Also, if anyone has a design that would still allow strings of lines or string pointers of li...
There are two main things making this slower than it could be, I think. The first, and probably less important: as you build up each line, you're appending words to the line. Each such operation may require the line to be reallocated and its old contents copied. For long lines, this is inefficient. However, I'm guessin...
5,332,946
5,332,989
Size of wchar_t for unicode encoding
is there 32-bit wide character for encoding UTF-32 strings? I'd like to do it via std::wstring which apparently showing me size of a wide character is 16 bits on windows platform.
You won't be able to do it with std::wstring on many platforms because it will have 16 bit elements. Instead you should use std::basic_string<char32_t>, but this requires a compiler with some C++0x support.
5,332,964
5,333,118
Comparing arrays of objects with arrays of fields of objects
Is there a good way to compare arr[i].A to A[i] and arr[i].B to B? int A[10], B[10]; class Foo { int A, B; }; Foo arr[10]; I could do the following: for (i=0;i<10;i++) { if (A[i] == arr[i].A) {} if (B[i] == arr[i].B) {} } But, this is painful especially if there are a lot of fields, and the if() condition...
IF the ranges are of equal size you can use std::equal with a predicate (or a lambda): bool CompA( int lhs, Foo rhs ){ return lhs == rhs.A; }; ... // to check for equality bool result = std::equal( A, A + 10, arr, CompA ); ... // to see where the mismatch is std::pair< int*, Foo* > result = std::mismatch( A, A + 10,...
5,332,971
5,333,067
C++: How would one implement their own String class?
I'm trying to re-learn C++ and was wondering if anyone could help me out here. I'm trying to implement my own String class to see if I can remember things, but I'm stuck on the constructor. I have my header file and want to have a constructor as so: Header File (MyFiles\String.h): #ifndef STRING_ #define STRING_ using...
Well, since it's a learning exercise. I think you want to copy the contents of the other string here since this is a copy constructor. So you will want to copy across all the member variables. In your case the copy constructor is not necessary because you've got a static array. If you had dynamic memory (i.e. used n...
5,333,113
5,333,141
How to pass a vector to a function?
I'm trying to send a vector as an argument to a function and i can't figure out how to make it work. Tried a bunch of different ways but they all give different error messages. I only include part of the code, since it's only this part that doesn't work. (the vector "random" is filled with random, but sorted, values be...
It depends on if you want to pass the vector as a reference or as a pointer (I am disregarding the option of passing it by value as clearly undesirable). As a reference: int binarySearch(int first, int last, int search4, vector<int>& random); vector<int> random(100); // ... found = binarySearch(first, last, search4, r...
5,333,159
5,333,211
Recursive copy constructor?
I'm attempting to write a copy constructor that takes a node of a quad tree, and copies that node, along with all its children, and its children, and so on. Here's what I have: Node(const Node & n) { nChild=new Node(*(n.nwChild)); neChild=new Node(*(n.nChild)); eChild=new Node(*(n.seChild)); wChild=ne...
Your constructor isn't exception-safe - suppose the second new throws bad_alloc, then how is the first one going to be cleaned up? You could probably make your own life easier by changing the Child fields to your favourite smart pointer. If you don't have a favourite smart pointer, introduce yourself to some ;-) [Edit:...
5,333,220
5,333,254
How to get gethostid behavior on windows 7?
I am porting a Linux code that uses <unistd.h>, specifically gethostid function, to Windows 7. I need an unique number of 32 bits that I will use in my application. How can I obtain an unique number using API from Windows 7 in the same manner that I do on Linux? Thanks.
You would normally implement this by returning the local IP address, for example by calling getaddrinfo().
5,333,267
5,346,164
How to compile the qt .uic file with Xcode?
How do I link up the C++ files with the .uic files in Qt?
*.ui are user interface files generated by designer. They are processed by uic. Try uic -h for help information. qmake will generate xcode project files by default or can generate Makefiles.
5,333,303
5,386,792
Excess elements in scalar initializer
(Updated with more code details) I'm pretty noobish when it comes to C++ STL stuff. After a compiler (LLVM GCC 4.2) upgrade, I'm getting: error: Semantic Issue: Excess elements in scalar initializer on the call: Certificate *tempcert; certMap cm; cm.insert( cValType( tempcert->id, tempcert ) ); with a typedef of: t...
It appears the confusion around this question was caused by buggy error messages in Xcode 4. After replacing a shared library generating errors (which were below the error in question), the error went away.
5,333,358
5,333,465
Initializing Class with {0}
I´m running a legacy c++ MFC software into DevPartner Studio and they complain a lot about these lines: PARAFORMAT pf = {0}; Where PARAFORMAT is a Class. Any class that is initialized this way, the DevPartner popups this error: Write Overrun: Memory write to 0x002B9D18 (152) overruns local variable pf 0x002B9D14 (156...
Without seeing PARAFORMAT, here's my take on what happens. PARAFORMAT is a POD struct/class with a size of 156 bytes. Your initializer syntax forces the compiler to generate code to initialize all members of the class. All members of the class will effectively have 0 written when initialized. So, the compiler sets the...
5,333,568
5,333,584
What is namespace used for, in C++?
What is namespace used for, in C++? using namespace std;
Namespace is used to prevent name conflicts. For example: namespace foo { class bar { //define it }; } namespace baz { class bar { // define it }; } You now have two classes name bar, that are completely different and separate thanks to the namespacing. The "using namespace" you show i...
5,333,574
5,333,581
Erase range from a std::vector?
If my std::vector has 100 elements, and I only want to keep the first 10 and erase the rest, is there a convenient way to do this?
vec.resize(10); // drops the rest (capacity remains the same)
5,333,619
5,333,666
How is nodejs different from running libevent?
I am curious what gives nodeJS the super concurrency that it gets right now. I have not actually used with either of these that much, just played with both in my spare time. Sounds like the 1000s of connections that node promises that you can set it up with, you can do that even with libevent, say in C++, no?
Sure you could. In fact, node.js is implemented using libev which is an event library similar to libevent. I think the main advantage of node.js over rolling your own event-driven server in C++ is that it's really easy to use and really easy to get a server up and running quickly without having to write all of the even...
5,333,871
5,333,962
Please explain this linking error: referenced in section .rodata
I am doing a build on a 32bit SLES10 machine. Using GCC 3.4.2 Here is a sample error `.L8245' referenced in section `.rodata' of CMakeFiles/myproj.dir/c++/util/MyObj.o: defined in discarded section `.gnu.linkonce.t._ZN5boost9re_detail9reg_grep2INS0_21grep_search_predicateIPKcSaIcEEES4_cNS_12regex_traitsIcEES5_S5_EEjT_...
This is typically due to 2 different .cpp's being compiled with different compiler switches - but also using the same templates. The generated template instantiations may differ in what they define/reference, and if the instantiation that is selected doesn't define/refer to the exact same symbols as the ones that got d...
5,334,180
5,334,238
What problems would you expect when switching from JS to C++?
What problems would you expect when switching from JS to C++ ?
C++ is incredibly different from Javascript. A few main differences: Static typing (usually types of variables are specified, most types are known at compile time) Low level memory management (no GC so you'll have to allocate and free a lot of memory yourself) Different object system: C++ is class-based, while Javascr...
5,334,195
5,334,685
Composing a set of container classes and accessing them from a base
I'm trying to use boost::mpl::inherit_linearly to compose a container class using types provided by the user: #include <typeinfo> #include <iostream> #include <vector> #include <boost/mpl/inherit.hpp> #include <boost/mpl/inherit_linearly.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/vector.hpp> names...
I think Base is a base class of InheritedContainer, but not of std::vector<int>. As we know, std::vector isn't defined as the following: class vector : Base {... You may expect the following inheritance: class InheritedContainer : Base, std::vector<int>, ... {... However, in this case, the cast from Base to vector<in...
5,334,268
5,334,294
Using bitwise operators in C++ to change 4 chars to int
What I must do is open a file in binary mode that contains stored data that is intended to be interpreted as integers. I have seen other examples such as Stackoverflow-Reading “integer” size bytes from a char* array. but I want to try taking a different approach (I may just be stubborn, or stupid :/). I first created ...
You want the bitwise left shift operator: typedef unsigned char u8; // in case char is signed by default on your platform unsigned num = ((u8)chars[0] << 24) | ((u8)chars[1] << 16) | ((u8)chars[2] << 8) | (u8)chars[3]; What it does is shift the left argument a specified number of bits to the left, adding zeros from t...
5,334,728
5,335,946
Link error with libpq using C++
I'm trying to use libpq to connect to my PostgreSQL database and intend to call pre-defined functions once I get this working. Right now I just have the conninfo string entered, and test the connection. After finally figuring out how to include different code directories and library paths (Netbeans 6.9.1 on Windows 7, ...
Someone else just had a similar issue with libpq. From the discussion that followed that answer, here's a link to download the source code so you can rebuild it to suit your needs. There are different versions available, so make sure you download the one you want. I really hate to just stick you with the dependency he...
5,334,771
5,334,920
Set boost::posix_time::duration to pos_infinite?
How does one set boost::posix_time::duration to positive infinite? The class contains an is_pos_infinite function, which retrieves duration::tick_type::pos_infinite for comparison, but I cannot work out how to retrieve this value and use it to set the duration.
Constructor takes some "special values": not_a_date_time, pos_infin, or neg_infin. time_duration td(pos_infin); Documentation for boost can be a pain to read...
5,334,783
5,336,813
Silly question about arrays in c and/or c++
Suppose I have two integer arrays a and b with 10 ints per array. Is there a way I can add the contents of b[i] to a[i] using some "memset" or "memcopy" trick? I'm just looking for something faster than the obvious for loop w/ a[i] += b[i] etc.
"Silly" - I think it's an excellent question! You say "adding" not "copying" and I'm assuming x86: void addintvector (int *dstp, const int *srcp, int nints) { int *endp; endp=dst+nints; nints=srcp-dstp; // reuse nints while (dstp!=endp) { *dstp+=*(dstp+nints); // makes use of the [base+index*4] x8...
5,334,852
5,334,894
C++ Variadic Macro To Specify Multiple Conditions
I suspect that I can't do this, but figured I'd ask the wise community here first. I want to check if any of a handful (say ten, though probably just two or three) of variables are equal to the same specific value. e.g. if (X == 3 || Y == 3 || Z == 3 || W == 3) ... In Python I'm used to simply doing if 3 in (X, Y, Z, ...
[The solution using a macro is at the end, because it's rather horrible and yucky.] If you don't mind copies being made, it's probably cleaner to use std::find: std::array<int, 4> values = { X, Y, Z, W }; if (std::find(values.begin(), values.end(), 3) != values.end()) { } It's often nice to wrap this line into a func...
5,335,060
5,335,107
help figuring out why this output is "01"
int main() { vector<int> v(5); v[0]=0; v[1]=1; v[2]=2; v[3]=3; v[4]=4; for (int i=0; i<v.size(); i++) v.pop_back(); for (int i=0; i<v.size(); i++) cout<<v[i]; cout<<"\n"; return 0; } i am confused as to why the output is "01". i would think the output is "0"
Trace each iteration of the first for-loop through: i v.size() v (before pop_back) 0 5 0,1,2,3,4 1 4 0,1,2,3 2 3 0,1,2 3 2 0, 1 And the loop stops there (not popping when i == 3) since 3 < 2 is false. So the final contents of v after the loop is [ 0, 1 ].
5,335,095
5,338,220
typename when defining map data that is a function pointer with a sprinkling of templates
This is a strange question because I already know the 'coding' answer. I just want to get a better understanding of why it is so. There are guru's here who have a knack of explaining these things better than the C++ standard :) Below we have a means to define an abstract factory template that allocates objects based on...
The standard tries to allow an implementation to parse and detect as many errors in a template as possible when it reads the template definition, before any instantiations. C++ is not context independent, however, and it's very difficult, if not impossible, to correctly parse statements if you don't know which symbols...
5,335,156
5,335,177
Overloading in C or not?
How does Variable Length Argument lists functions like printf() , scanf(), etc in C differ from Function Overloading in C++? And how does the call printf("Didnt Work %s",s); differ from printf(s,"Didnt Work %s"); where s is defined as: const char *s="string"; Please Explain.
In const char *s="string"; printf(s,"Didnt Work %s"); The first argument "string" is interpreted as the format string. It has no insertion codes, so the second parameter won't ever be used. The result will be "string". OTOH printf("Didnt Work %s",s); There is an insertion code, so the second argument gets inserted ...
5,335,637
5,335,657
How to erase duplicate element in vector, efficiently
I have vector<string> data ; // I hold some usernames in it In that vector, I have duplicate element(s), so I want erase this/these element(s).Are there any algorithm or library function to erase duplicate element(s)? ex : In data; abba, abraham, edie, Abba, edie After operation; abba, a...
If you can sort the elements in the container, the straightforward and relatively efficient solution would be: std::sort(data.begin(), data.end()); data.erase(std::unique(data.begin(), data.end()), data.end());
5,335,836
5,335,847
why a const object of an empty class cant be created
#include <iostream> class A { public: void foo() const { std::cout << "const version of foo" << std::endl; } void foo() { std::cout << "none const version of foo" << std::endl; } }; int main() { A a; const A ac; a.foo(); ac.foo(); } The above code can't be compi...
You need to initialize it. This is a known problem with the spec.
5,336,085
5,336,142
c++ namespace problem
hi can any one help me with this code. i'm new to c++ #include <stdio.h> #include<iostream> using namespace std; namespace manish { double mean(double a, double b); } double mean(double a, double b) { return (a+b) / 2; } i want to make a static libray for this i use the command g++ calc_mean.cpp -o mean.o it ...
You are using -o which means the compiler expects the files to create a complete program. However, a complete program must contain a main() function. You should use: g++ -c calc_mean.cpp If you do not have a main function.
5,336,383
5,336,410
Whats wrong with the following code? It's not compiling
#include <iostream> #include <vector> using namespace std; class Base { public: void Display( void ) { cout<<"Base display"<<endl; } int Display( int a ) { cout<<"Base int display"<<endl; return 0; } }; class Derived : public Base { public: ...
You need to place - using Base::Display ; // in Derived class If a method name is matched in the Derived class, compiler will not look in to the Base class. So, to avoid this behavior, place using Base::Display;. Then the compiler will look into the Base class if there is any method that can actually take int as argu...
5,336,403
5,372,742
Is there any way to set a breakpoint in gdb that is conditional on the call stack?
I am debugging C++ in gdb 7.1 on Linux. I have a function a() that is called in many places in the code. I want to set a breakpoint in it, but only if it was called from b(). Is there any way to do it? Is there any way to do it only if b() was called from c(), and so on ad infinitum?
Update: There is now a better answer to this question: use GDB _is_caller convenience function. The need you describe comes up quite often, usually in the context of some_utility_fn being called a lot, but you only are interested in the call which comes from some_other_fn. You could probably script this entire interact...
5,336,405
5,336,462
realloc failing to allocate
i am using VS08 to build/run the following c++ code: #include <stdlib.h> struct Header { int count; }*lstHeader=NULL; int main() { for(int i=0;i<10;i++) { lstHeader=(Header*)realloc(lstHeader,sizeof(Header)+i); lstHeader[i].count=i; } return 1; } and after running i get the fol...
You need to think of what happens when i gets to 1. Let's assume a four-byte integer. At i == 0, you allocate enough bytes for one Header plus an extra zero bytes. Then you set Header[0].count to 0. No problems there, you've only changed the four bytes you allocated. At i == 1, you allocate enough bytes for one Header ...
5,336,498
5,336,636
HowTo create template of a container (e.x. std::map)?
So, I had a simple working code, for example template <typename T, typename VALUE> VALUE mapAt(T key) { std::map<T, VALUE>::const_iterator item_i(MyMap.find(key)) , end_i(MyMap.end()); if (item_i == end_i) { throw std::exception("No such key!"); } retur...
You can write something like this: template <class Container> typename Container::mapped_type mapAt(Container& MyMap, typename const Container::key_type& key) { typename Container::const_iterator iter = MyMap.find(key); return iter->second; } int main() { std::map<int, char> my_map; char ch = mapAt(my_...
5,336,547
5,336,571
Check whether stdin/std::cin support seeking
EDIT: I had a stupid bug in the code and fixed this, so things are explicable now. I updated my post accordingly. The following code shows that seeking within the line buffer works. First, the result when piping something into the program. $ echo 'asdf' | ./seektest stdin does not support fseek() c == s std::cin does n...
Looks to me like you have your condition reversed here: if (std::cin.fail()) { fprintf(stdout, "std::cin supports seekg().\n"); } else { fprintf(stdout, "std::cin does not support seekg().\n"); } std::cin "supports seekg()" if it failed?
5,336,834
5,339,737
How to wait on a Mutex with OpenMP
I've a for loop that will launch processes in parallel every launched process will return a response back indicating that it is ready. I want to wait for the response and I'll abort if a certain timeout is reached. Development environment is VS2008 Here is the pseudo code: void executeCommands(std::vector<Command*> com...
As the comment above pointed out, Michael Suess did present a paper on adding this functionality to OpenMP. He is the last of several people that have proposed adding some type of wait function to OpenMP. The OpenMP language committee has taken the issue up several times. Each time it has been rejected because there...
5,336,942
5,337,551
Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type:
I'm trying to expose my C++ Classes to Python using Boost.Python. Here is a simplyfied version of what i'm trying to do: I have a class A deriving from boost::noncopyable and a second class B with a method that takes a reference to A as an argument. class A : boost::noncopyable { /*...*/ }; class B { public: vir...
Change B.do_something(a); to B.do_something(boost::ref(a));. See Calling Python Functions and Methods in the boost manual.
5,337,108
5,337,172
How does the linker knows which symbol to which one link?
Say I have two .cpp files and in one of them I wrote extern int i ; and in another one I define the i variable. Now how the linker knows that in the first file the i should be linked to the address of "i" in the second file? This question arises, because as I know, the object file does not have any info about variabl...
The object code has symbol definitions in it. The linker uses these to resolve references to symbols. The symbols are not part of the executable code, and cannot be read by code that is contained within the object file (hence the answer to the question to link to). The linked executable may also have symbols in it (e.g...
5,337,370
5,337,391
Redefinition allowed in C but not in C++?
Why does this code work in C but not in C++? int i = 5; int i; // but if I write int i = 5; again I get error in C also int main(){ // using i }
Tentative definition is allowed in C but not in C++. A tentative definition is any external data declaration that has no storage class specifier and no initializer. C99 6.9.2/2 A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storag...
5,337,573
5,342,013
How to contact parent process from child in QT (C++) to perfom method from class?
I have a question. I'm currently working on program in QT (C++) and I have this problem. If I check the checkbox, it starts a method, where is implement fork (). Parent process continues to the end (to keep unfrozen GUI). A child process works in ifinite loop. After completing a sequence, I store the necessary data int...
The way I would probably approach this problem would be to have the GUI operating in the main thread and then to have a QThread started when the checkbox is checked. This QThread can run continuously or be stopped and restarted with the checkbox depending on the requirements. Once the process has completed, if the amo...
5,337,718
5,338,050
Is this program is correct -->using C++0x N3242
A class is a type. Its name becomes a class-name (9.1) within its scope. class-name: identifier simple-template-id Class-specifier s and elaborated-type-specifier s (7.1.6.3) are used to make class-names. An object of a class consists of a (possibly empty) sequence of members and base cla...
It looks like it would be ok, but I don't think any compiler implements this yet. It is also subject to change, as there is a request to remove this: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3234.pdf
5,337,755
5,337,803
How to assign char array in struct inline?
I'm trying to do something like this: struct SomeStruct { const char *bytes; const char *desc; }; SomeStruct example = { { 0x10, 0x11, 0x12, 0x13 }, "10-13" }; Why isn't this working?
Probably because { 0x10, 0x11, 0x12, 0x13 } is an array of char, not a pointer to char. Try SomeStruct example = { "\x10\x11\x12\x13", "10-13" }; instead.
5,337,824
5,338,012
Binding to Loopback Adapter in Windows 2008 Server
For testing purposes, I'm trying to run a number of client applications connecting to a server all on the same host machine. The host machine is running Windows 2008 Server Standard 32-bit with Service Pack 2. On my XP development machine I installed the Microsoft Loopback Adapter in order to run multiple clients conne...
Ok, problem solved. I was specifying that the client connect to 127.0.0.1 but when I asked it to connect to a 192.168.5.x address it worked. The server was bound to 0.0.0.0 which suggests that it should still have been bound to 127.0.0.1 anyway but it just didn't seem to work!
5,337,876
5,337,986
Optimisation on lookup question
The requirement is that a number of 'clients' select a range of resources which they wish to control and listen to events on. Typically there would be 10 or so clients and 100 or so resources. It is possible that the number of clients and resources could be 1000 plus however. This is currently implemented as a map ...
your structure looks like {client:[resource]} but for efficient event delivery you need {resource:[client]}
5,338,185
5,338,818
File parsing: C++ to cocoa
Can anyone help me to convert this c++ function to cocoa? Here I am parsing file line by line. I need to know efficient NS function std::ifstream Stream; Stream.open(FilePath,std::ios_base::in); if (Stream.is_open()) { std::string Line; std::string Read, Key, Value; std::size_t i; while( !Stream.eof()...
approximately: NSString * file = [[NSString alloc] initWithContentsOfFile:path]; // or url NSCharacterSet * newlineSet = [NSCharacterSet newlineCharacterSet]; NSArray * lines = [file componentsSeparatedByCharactersInSet:newlineSet]; for (NSString * at in lines) { printf("%s\n", [at UTF8String]); } [file release], fil...
5,338,335
5,338,377
Undefined reference from virtual function
I have a class like: Base.h class Base { public: Base(); virtual int getInfo(int i); protected: int GetDetail (int iVal); } inline int Base::getInfo(int i){ int output = GetDetail(i); return output; }; Ib Base.cpp, I have the GetDetail defined. int Base::GetDetail(int i){...
Remove the inline specifier in front of int Base::getInfo(int i) and try (:
5,339,107
5,339,189
Static objects are not being linked in a static lib in VC 2010. How do I force a link?
I have a static factory that relies on a static member of itself to register the class into the factory system. class Foo_A_Maker : public FooFactory<Foo, const std::string &> { private: // Register this as a type using a static instance of itself. // This is really the only time it is created. That's why the ...
This is how libs are supposed to work - the linker only takes the symbols it needs (referenced from the outside). The correct way of solving this is to provide an init function. For Visual Studio you can find the exact symbol name that you need, and pass /INCLUDE as a command-line option to the linker. You can try wit...
5,339,200
5,339,606
How to create a single instance application in C or C++
What would be your suggestion in order to create a single instance application, so that only one process is allowed to run at a time? File lock, mutex or what?
A good way is: #include <sys/file.h> #include <errno.h> int pid_file = open("/var/run/whatever.pid", O_CREAT | O_RDWR, 0666); int rc = flock(pid_file, LOCK_EX | LOCK_NB); if(rc) { if(EWOULDBLOCK == errno) ; // another instance is running } else { // this is the first instance } Note that locking allow...
5,339,395
5,339,432
Incompatible function declaration
I'm stuck, why am i getting an error: declaration is incompatible... 'void A::function(int,int,std::vector<_Ty> *)' : overloaded member function not found in 'A' error C2061: syntax error : identifier 'vector' 1> with 1> [ 1> _Ty=Point 1> ] //cpp file void A::function(int a, int...
It's because the header of the function should be exactly the same. //cpp file void A::function(int a, int b, vector<B>* c) { } //header file Class B { public: int q; }; class A { public: void function(int a, int b, vector<B> *line); }; or : //cpp file void A::function(int a, int b, vector<B>& ...
5,339,747
5,339,880
How to resolve this using STL?
I have this problem: There are 5 people, in a matrimonial, to obtain the best choice each of them are told to answer some 10 multiple choice questions with 4 options: A, B, C, D. Now the best match refers to the person having highest "similarity factor" (sf). E.g if Dick and Lisa have got 6 answers correct, and sf=3 (...
I don't know if this is what you want, but if you get all the answers into a valarray<std::string>, you can compare these directly. The result is a valarray<bool>, which contains true if the corresponding elements were equal, and false otherwise. You can then count how often they were equal using: std::valarray<bool> =...
5,339,811
5,340,065
How can i pass C++ Objects to DLLs with different _ITERATOR_DEBUG_LEVEL
My executable makes calls to a number of DLLs, that i wrote myself. According to 3rd party C++ libs used by these DLLs i can not freely choose compiler settings for all DLLs. Therefore in some DLLs _ITERATOR_DEBUG_LEVEL is set to 2 (default in the debug version), but in my executable _ITERATOR_DEBUG_LEVEL is set to 0, ...
The problem is that std::string and other containers are template classes. They are generated at compilation time for each binary, so in your case they are generated differently. You can say it's not the same objects. To fix this, you have several solutions, but they are all following the same rule of thumb : don't exp...
5,339,950
5,340,164
Is it possible to dynamically create an array of constant size in C++?
First of all, I want to reassure you all that I am asking this question out of curiosity. I mean, don't tell me that if I need this then my design has problems because I don't need this in real code. Hope I convinced you :) Now to the question: For most types T we can write T* p = new T; now what if T is an array type...
The reason you can't do it is that new int[3] already allocates exactly what you want, an object of type int[3]. It's just that what the new-expression returns, is a pointer to its first element. 5.3.4/1: If the entity is a non-array object, the new-expression returns a pointer to the object created. If it is an ...
5,339,987
5,340,098
Needed: A popup window without a taskbar icon
I am designing a UI engine that needs to render into popup (WS_POPUP) windows. As these windows cannot be children of other windows, each instance is given its own taskbar icon. I need a way to prevent the taskbar icons from appearing for certain windows that are created as "dialogs". I cannot use an OS-provided dialog...
If you set the WS_EX_TOOLWINDOW extended style for your window, it won't be shown in the task bar or Alt+Tab list. This does cause the window to be rendered slightly differently, however (thinking floating tool palette).
5,340,173
5,340,211
Handling Out-of-Range Indices
For a container class, what should the expected behavior be when the user of the class tries to set a value that's outside the class's size? The method in question is a "replace" method (like operator[]), rather than an "add" method (like operator+=). I could throw an out_of_range exception or I could just resize the c...
An out of range exception is more appropriate here because "replace" semantics normally means that the caller is presuming/asserting there is data at the specified index, which there is not.
5,340,312
5,340,367
How do I get the module handle of the satellite resource DLL? (c++ visual studio )
We have moved all our strings to resources (and satellite DLLs) for an MFC application. Right now the primary language is incorporated into the EXE itself so when I call LoadString() I can just pass in the module handle of the exe. However, I need to make this generic - how do I get the module handle in a generic wa...
After you've loaded the resources dll with LoadLibrary, you store its HMODULE (returned by LoadLibrary) and pass it to the LoadString function (as well as to the other resource functions). By the way, if you use your resources DLLs exclusively to store resources (i.e. no code is included in them) you can load them with...
5,340,452
5,348,789
Set active printer in PrintOut OLE function
I use PrintOut function Excel::_ApplicationPtr app("Excel.Application"); app->Visible[0] = false; Excel::_WorkbookPtr book = app->Workbooks->Add(); Excel::_WorksheetPtr sheet = book->Worksheets->Item[1]; .... book->Worksheets->PrintOut(1, 1, 1, false, NULL, NULL, NULL, false, false); But it's wrong. The defeniton o...
According to this MSDN article Active Printer is in fact the name of the printer you want to use, so it is a string and it is also an optional parameter, so I guess you can just pass empty variant there: book->Worksheets->PrintOut( .., _variant_t(), ... );
5,340,744
5,340,865
Is constant integer division optimized out by the compiler?
First I feel I must defend myself. I know I should probably not worry about this kind of thing, premature optimization and what-not. I know. I am asking this purely because I'm curious and couldn't (or don't know how) find the solution myself. Is it common practice for compilers to optimze away constant integer divisio...
Yes it is virtually universal practice, in fact if your compiler doesn't do it you have a very unusual compiler indeed.
5,340,928
19,291,620
Utilities for creating a lock hierarchy?
According to the answers found in Threads and simple Dead lock cure and also Herb Sutter the key to avoiding deadlock is by using lock hierarchies. Are there any good C++ libraries that provide support for this? I can't find any in Boost or Poco. Ideally it would be a system that allows one to define the hierarchy at c...
Yes, lock hierarchies can effectively prevent deadlocks; of course whether you can actually define a hierarchy for your program (especially, in the presence of plugins) is another matter entirely. The basic blocks are simple: Each mutex should have a level (either determined at compile-time or run-time) Each thread sh...
5,340,991
5,341,145
What's the most efficient way of reading an ifstream into an string?
noob question! How can i read 'a whole ifstream' into a stdlib 'string'? The current way i'm using for all my projects right now wastes much time i think: string code; ifstream input("~/myfile"); char c1=input.get(); while (c1!=EOF) { code+=c1; len++; c1=input.get(); } BTW i prefer to do line and whitespac...
string load_file(const string& filename) { ifstream infile(filename.c_str(), ios::binary); istreambuf_iterator<char> begin(infile), end; return string(begin, end); }
5,341,067
5,342,735
C++ DLL which can inform a calling program about its progress
My boss wants me to write a DLL in C++ (MSVC++2010) which can perform a Volume Shadow Copy which he can call from VB6 (or at a later point other languages) and which can give status updates back while it is not finished. He calls it "events". I have the feeling that I finally need to learn COM (I'd rather not ...) ... ...
You can pass a pointer to your "display progress" function from the VB app to the C++ DLL app using the AddressOf operator: Declare Function CallMyDll ... Sub DisplayStatus(ByVal SomeParameter As Long) ' ... End SUb Sub DoSomething() Call CallMyDll(AddressOf DisplayStatus) End Sub Some not so obvious gotchas...
5,341,123
5,341,155
C++: something is getting sent to the console: how do I, instead, store it to a variable?
string convert_binary_to_hex(string binary_value) { bitset<8> set(binary_value); cout << hex << set.to_ulong() << endl; // this is the output that I want to store to a variable to return return ""; } I've not really done C before. =D EDIT: a user suggested ostringstream: ostringstream result; bitset<8>...
Write it to an instance of std::ostringstream: string convert_binary_to_hex(string binary_value) { bitset<8> set(binary_value); ostringstream oss; oss << hex << set.to_ulong() << endl; // this is the output that I want to store to a variable to return return oss.str(); }
5,341,191
5,341,318
Confused about namespace scope!
I'm getting confused about the scope of 'using namespace' declarations... hoping someone can clear this up for me! I'm using two libraries (OpenCV and Ogre3D). I have two cpp files, one uses exclusively OpenCV (PoseEstimator.cpp) and the other exclusively Ogre3D (OgreLogic.cpp). The top of OgreLogic.cpp looks like this...
It looks like what is happening is you have a line declaring a uchar, e.g. uchar x = 12 or something. At the top of your file, you've specified that you're using the Ogre namespace. The compiler is running into a problem determining which uchar you're using - the cxtypes.h one or the Ogre::uchar. Try taking out the usi...
5,341,395
5,341,667
new[] doesn't decrease available memory until populated
This is in C++ on CentOS 64bit using G++ 4.1.2. We're writing a test application to load up the memory usage on a system by n Gigabytes. The idea being that the overall system load gets monitored through SNMP etc. So this is just a way of exercising the monitoring. What we've seen however is that simply doing: char* ...
Please look up for overcommit. Linux by default doesn't reserve memory until it is accessed. And if you end up by needing more memory than available, you don't get an error but a random process is killed. You can control this behavior with /proc/sys/vm/*. IMO, overcommit should be a per process setting, not a global o...
5,341,396
5,341,465
"Cannot appear in a constant expression", I need this to be a variable, why won't it let me?
string convert_binary_to_hex(string binary_value, int number_of_bits) { bitset<number_of_bits> set(binary_value); ostringstream result; result << hex << set.to_ulong() << endl; return result.str(); } In the above method, I am converting binary strings to hex strings. Since hex values are 4 bits, the...
You can't. Template parameters like that need to be known at compile time since the compiler will need to generate different code based on the values passed. In this case you probably want to iterate through your string instead and build up the value yourself, e.g. unsigned long result = 0; for(int i = 0; i < binary_va...
5,341,661
5,343,180
How can I fix this vs10 inconsistent dll linkage warning?
I have a series of warnings that I'm trying to fix when building gdcm using visual studio 10 (32 bit version): 4>..\..\..\..\gdcm\Utilities\gdcmexpat\lib\xmlparse.c(647): warning C4273: 'XML_ParserCreate' : inconsistent dll linkage 4> d:\src\gdcm\gdcm\utilities\gdcmexpat\lib\expat.h(206) : see previous definit...
No, it is complaining about __declspec(dllimport) missing from the function definition but present on the function declaration. You ought to take this seriously, it doesn't make sense to declare the function imported from a DLL but also present in your code. You can't have it both ways. This is usually caused by a mi...
5,341,850
5,341,924
WTL way of forcing resources to load from a dll in a non mfc app? (we are using WTL/ATL, not straight win32)
I posted this question previously and now have the localized strings loaded (the ones we get with LoadString()) but I also need to load all the other resources from the satellite DLL. MFC has the AfxSetResourceHandle () call, but I need something equivalent for a non-mfc app? I suspect I have to set that in the initia...
The resource functions (FindResource, LoadResource) take a handle to a module as one of the parameters. Use GetModuleHandleEx to get the module handle for the DLL. Edit: Additional info for ATL/WTL. WTL uses ATL::_AtlBaseModule.GetResourceInstance() for the module handle in its Win32 calls. There's a SetResourceInstanc...
5,341,919
5,342,030
Writing to file in iOS using C/C++
Is it possible to create a text file using C/C++ calls in iOS? Is it then possible to open and read the file from outside the application? That is, application A creates a text file somewhere it has permissions to write to and application B then reads from it. Or, forget application B, can I just open it and read?
Yes. Use NSFileHandle to get read/write access to files and NSFileManager to create directories and list their contents and do all other sorts of file system access. Just keep in mind that every App is sandboxed and can only write to its own designated directories. You can get the path to these directories with code li...
5,341,925
5,341,981
Linux Low Level Mouse Reading
I want to read mouse position and button state in Linux with C++, but without X or some (high-level) library etc. The only two possibilities I found are reading from the device /dev/input/mice (with fopen,...) or using libgpm. Are there other low level methods? Thanks ahead.
In Linux all mouse events go through /dev/input/mouseX. /dev/input/mice is an accumulator in the single mouse devices. Both gpm and X fetch mouse events from /dev/input/mouseX or /dev/input/mice and forward it. So reading from /dev/input/mouseX or /dev/input/mice is as low level as you can get – unless you're using lib...
5,341,926
5,341,959
C++ how to get a static variable in a class?
I can't get the syntax correct for with static variables and c++ classes. This is a simplified example to show my problem. I have one function that updates a variable that should be the same for all objects, then I have another functions that would like to use that variable. In this example I just return it. #include ...
Your commented out code is halfway there. You also need to define it outside the class with a int Nisse::cnt = 0; statement. EDIT: like this! class Nisse { private: static int cnt; public: ... }; int Nisse::cnt = 0;
5,341,935
5,341,990
What happens when a short int[] is automatically cast to long int[]?
In C++, if I have an array of short ints and pass it as an argument to a function that takes an array of long ints, will the function see each value of the short array cast to a long int or will the entire array be reinterpreted into an array of long ints of n/2 elements?
You can't because there's no automatic cast that can be used. Remember that you can't pass an array to a function by value: an array parameter is really just a pointer parameter, so the following two are the same: void f(long a[]); void f(long* a); When you pass an array to a function, the array is implicitly convert...
5,342,012
5,342,290
Handling Linux Network Connectivity in Java/C++?
I am working on a program to handle connections in Ubuntu. I am currently doing it in Java, but aim to do it in C++ too. Essentially, atm I am just running system commands through Java: proc.exec("ifconfig wlan0 down"); etc. I get some printout saying it is 'deconfiguring interfaces' and 'fail' is printed out. First ...
Probably you can try to interface NetworkManager, which uses D-Bus as its interface, and there exists Java implementations of the protocol.
5,342,045
5,342,186
C++: How does one replace all instances of a character in a string with another character?
I found this method on the internet: //the call to the method: cout << convert_binary_to_FANN_array("1001"); //the method in question: string convert_binary_to_FANN_array(string binary_string) { string result = binary_string; replace(result.begin(), result.end(), "a", "b "); replace(result.begin(), result.end(), "...
You need characters, not strings, as the third and fourth arguments to replace. Of course that won't do if you really want to replace 'a' with "b ". So, e.g., string convert_binary_to_FANN_array(string binary_string) { string result = binary_string; replace(result.begin(), result.end(), 'a', 'b'); replace(...
5,342,063
5,342,138
replace single quotes in string with \'
I have a string that contains ' characters. I want to replace all of them with \' as this is used for inserting into the database. Can some one suggest me an efficient way to do this? Unfortunately, I cannot use boost and limited to STL.
Don't forget to also escape \ when it occurs in the source string. std::string escape(std::string const &s) { std::size_t n = s.length(); std::string escaped; escaped.reserve(n * 2); // pessimistic preallocation for (std::size_t i = 0; i < n; ++i) { if (s[i] == '\\' || s[i] == '\'') ...
5,342,511
5,342,539
C null pointer with string literals
Using an ARM, C compiler, I can successfully compile and run the following: static char * myString = 0; void myfunc(int x){ if (x <= 0) myString = "Hello World"; else myString = "This is a different string with a different length"; } int main(){ myfunc(-1); printf("%s\n", myString); ...
The two strings ARE allocated in read-only memory and are completely different. But you use one and the same pointer to point to each of them... What's not to understand? Remember, char* is just a pointer. It is mutable (non-const). char* p = 0; p = "Hello"; //OK p = "Jo" //OK; p[0] = 'X' //OOPS, now THIS is bad (unde...
5,342,550
5,342,569
How to sort "vector" which contains class objects? And why I am wrong?
Today I wrote some codes about using std::sort() to operate a "vector" type which contains class objects, but I found many problems in coding, please help me to find solution: #include <vector> #include <algorithm> class Obj{ private: int m_; public: Obj():m_(0) {} int act() { return m_; } bool operat...
When using std::sort you can optionally pass a comparator, like you do. If you don't, std::sort will use std::less as a comparator, std::less defaults to use operator<. You can use your cmpA functor, but then you can only access const member functions of the passed objects - you have a const reference to them in cmpA. ...
5,342,596
5,342,660
c++ vector bad access
Hi I have the following c++ program: #include <iostream> #include <fstream> #include <vector> #include <sstream> #include <boost/foreach.hpp> #include <stdexcept> #include <boost/flyweight.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; struct entry { int file;...
This line: std::vector<entry> data; creates an empty vector, which you are passing to my_file and accessing data[i] within. You need to reserve space for the elements before you can access arbitrary indices in the vector. For example: std::vector<entry> data(maxItems);
5,342,659
5,342,743
Understanding C++ Compilation
I have recently become aware that I have no idea, genericly speaking, how a c/c++ compiler works. I will admit this initialy came from trying to understand header guards but came to the realization that I am lacking in how compiling works. Take Visual C++ for instance; Theres the "Header Files" folder, the "Resources...
Your questions aren't really about the compiler, but about how your IDE is handling the entire build system. The build systems for most C/C++ projects compile each .c or .cpp file separately, and then link the resulting object files together into a final executable. In your case, your IDE is compiling any file you ha...
5,342,790
5,343,085
Automake Yacc Output Filename Quandary
Problem: I have a project which I'm porting from Solaris/Lex/Yacc to Linux/Flex/Bison + Autotools. I'm running into the following issue, and I wonder if anyone out there knows how to get around it. Given a target like so (only necessary details included): bin_PROGRAMS=my_prog my_prog_YFLAGS=-d my_prog_SOURCES=\ mai...
Solution: So it took me actually reading through the automake source itself (for the curious, look at the handle_single_transform function). If there are per-target options specified for a given source-type, automake automatically prepends the project name to any generated files. Therefore, changing: my_prog_YFLAGS=-d ...
5,343,035
5,343,055
Why isn't cin >> string working with Visual C++ 2010?
#include <iostream> using namespace std; int main() { string s; cin >> s; cout << "Hello World!"; } This isn't working. Why?
Because you forgot to #include <string>
5,343,173
5,343,199
Returning to beginning of file after getline
So i've read all the lines from a file thusly while (getline(ifile,line)) { // logic } Where ifile is an ifstream and line is a string My problem is I now want to use getline over again, and seem to be unable to return to the beginning of the file, as running cout << getline(ifile,line); Will return 0...
Since you have reached (and attempted to read past) the end of the file, the eof and fail flags will be set. You need to clear them using ifile.clear – then try seeking: ifile.clear(); ifile.seekg(0);
5,343,190
5,343,250
How do I replace all instances of a string with another string?
I found this on another stack question: //http://stackoverflow.com/questions/3418231/c-replace-part-of-a-string-with-another-string // void replaceAll(std::string& str, const std::string& from, const std::string& to) { size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { ...
The bug is in str.replace(start_pos, end_pos, to); From the std::string doc at http://www.cplusplus.com/reference/string/string/replace/ string& replace ( size_t pos1, size_t n1, const string& str ); You are using an end-position, while the function expects a length. So change to: while((start_pos = str.find(from, s...
5,343,193
5,345,243
boost to_upper char pointer in one expression
Is it possible to do something like: const char* str = "AaBbCc"; string str_up = boost::to_upper_copy(str); // str_up will be "AABBCC" Last line doesn't compile. Of course I can as below, but it less "canonical": const char* str = "AaBbCc"; string str_up = str; boost::to_upper(str_up);
Why not post the right solution as an answer to the question? const char* str = "AaBbCc"; std::string str_up = boost::to_upper_copy(std::string(str)); Credits to Konrad.
5,343,437
5,343,447
Meaning of "~" (tilde) symbol in C++?
// AirlineTicket.h class AirlineTicket { public: AirlineTicket(); ~AirlineTicket(); int getNumberOfMiles(); private: int mNumberOfMiles; }; I want now what is the meaning of ~AirlineTicket(); in this code? I don't know the meaning of ~ (tilde).
It is the destructor. It gets called when you destroy (reaching end of scope, or calling delete to a pointer to) the instance of the object.
5,343,473
5,421,727
Convert simple MFC CView/CDocument/CSingleDocTemplate app to ActiveX control
I have a fairly simple MFC app that just defines its own sub-classes of CDocument, CView and CFrameWnd and uses them via a CSingleDocTemplate to display the read-only contents of the document in a tree on the view. All very standard MFC MVC. I now need to convert this app so that it works as an ActiveX control that I c...
Answering my own question: I found quite a few references to an old article about this, which used to be at http://www.microsoft.com/mind/0497/mfc.asp but has long since disappeared. :( Fortunately though, the Wayback Machine still has a complete copy of it: "Designing ActiveX Components with the MFC Document/View Mode...
5,343,660
5,343,729
struct which a HANDLE points to
I tried without success to find information about the structs that HANDLEs point to. For example, CreateFile() returns a HANDLE (== void*) that I think points to a struct with information about the file. Same thing for processes and threads and every HANDLE. So, where can I find information about the structs that the H...
The HANDLE type in WINAPI is an opaque pointer utilized to hide implementation details from the programmer. It is usually a bad idea to write code that depends on the internals behind an opaque pointer since one of its uses is the ability for the API provider to change those internals without breaking any user code. Ev...
5,343,721
5,343,740
can't modify char* - Memory access violation
Why does it say "Memory access violation"? char* str = "HelloGuys"; int len = strlen(str); for (int i=0; i<(len/2); ++i){ char t = str[len-i-1]; str[len-i-1] = str[i]; //error str[i] = t; }
String literals are stored in read only section of memory. Any attempt to modify the contents of a string literal invokes Undefined Behaviour (segmentation fault on most implementations). Use an array of characters rather char str[] = "HelloGuys";
5,343,846
5,347,748
How to display this data buffer in a QImage
I have an image I am trying to display in a QImage. This is the snippet of code that populates the rows*cols image: rgbMapped[row][col * 3] = red; rgbMapped[row][col * 3 + 1] = green; rgbMapped[row][col * 3 + 2] = blue; As you can see, my data buffer is "rows-high" and is "cols*3 wide" rgbMapped is an un...
Just an assumption, but from the (wrong) colors you mentioned, I suspect the problem could be with your allocation/initialization code regarding the char **rgbMapped variable. Could you please post this code? I will try to write bellow a possibly correct(?) initialization code just to give you a hint which may help (I...
5,343,889
5,344,415
Recursive C++ Combinatorics: Not sure how to get the results in order
I have a function to print all of the ternary string combinations from length 0 to length n: void TerString(int len,string input){ printf("\n%s",input.c_str()); if (input.length()<len){ TerString(len,input+"0"); TerString(len,input+"1"); TerString(len,input+"2"); return; } ...
Note that all the strings of the same length are already in the right order. And the example you gave isn't lexicographical order at all, it's ordered by length. Lexicographical order (i.e. dictionary sort) is what you're already seeing. To get results sorted by length, iterate by length first, and generate only stri...