question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,458,162
2,458,215
How to get this to compile?
I have this code which compiles and works as expected: class Right {}; class Left { public: Left& operator = (Right const&) { //... Do something ... return *this; } }; int main() { Right right; Left left; // Assign individual object -- this works left = right; } But now, this one surprises m...
Use: std::copy(rightLst.begin(), rightLst.end(), std::back_inserter(leftLst)); This will add new elements to the end of leftLst corresponding to the elements in rightLst. You will need to add a constructor to Left that takes const Right &. If leftLst and rightLst already contain the same number of elements and you w...
2,458,232
2,458,587
Adjust parameters of serial port reading
I'm facing a particular issue that regards serial communication under win32. I'm communicating with a device can only accept frames when it is not already communicating. So I must find a valid frame and then inmediatelly send my request. I developed a class named Serial that handles basic operations on serial port (ope...
I'm not sure if this will help or not, but since you already have a good idea of how many bytes are in the serial device's input queue (stat.cbInQue) maybe it would help to read in that many bytes instead of just 1 byte or an arbitrary number of bytes (like 50): bool ok = ::ReadFile( handle, buffer_in, stat.cbInQue, &b...
2,458,372
2,458,761
C++ compile time purity checks?
Is it possible to specify compile time "purity" checks in C++? I.e.: this function does not read from anything other than it's arguments this function does not write to anything; it only returns the return value
const-correctness and high compiler warning levels should do a lot of what you are asking for. Also specifying a very strict modern dialect of C++ for the compiler ( which can annoy the hell out of you, when you are using third-party libraries and code that dont comply ) If not, then there are a plethora of static anal...
2,458,381
2,458,403
Using type passed as a template in C++
Is it possible to actually use the type passed as a template for control flow? I'd like to write a function that uses templates, which in turn calls another function based on the type passed: template <class T> void test_function (T var) { //Do stuff if (T == char) { bar (var); } else { foo ...
You usually use specialization for that: template<class T> void forward(T t) { // ... } template<> void forward<char>(char c) { // ... } template<class T> void test(T t) { forward<T>(t); } This gives you effectively "compile-time branching".
2,458,459
2,458,475
Why friend function is preferred to member function for operator<<
When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ? class A { public: void operator<<(ostream& i) { i<<"Member function";} friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;} }; int main () { A a; A b; A c; cout<<a<<b<<c...
You have to use a free function and not a member function as for binary operators the left hand side is always *this for member functions with the right hand side being passed as the other parameter. For output stream operators the left hand side is always the stream object so if you are streaming to a standard class a...
2,458,617
2,458,683
OO Design - polymorphism - how to design for handing streams of different file types
I've little experience with advanced OO practices, and I want to design this properly as an exercise. I'm thinking of implementing the following, and I'm asking if I'm going about this the right way. I have a class PImage that holds the raw data and some information I need for an image file. Its header is currently som...
Yes, you could implement your class hierarchy in the way you describe. Nevertheless, I would probably have had PngImage, GifImage and JpegImage derive directly from PImage. PImage can then become abstract: class PImage { virtual ~PImage {} virtual unsigned int getWidth() const = 0 virtual unsigned int getHeight()...
2,458,637
2,458,665
Boost link error when using "--layout=system" on VS2005
I'm new to boost, and thought I'd try it out with some realistic deployment scenarios for the .dlls, so I used the following command to compile/install the libraries: .\bjam install --layout=system variant=debug runtime-link=shared link=shared --with-date_time --with-thread --with-regex --with-filesystem --includedir=<...
Fast answer, for I have no access to a Visual C++ at home. I believe you are clashing with the "autolinking" of Boost on Visual C++ compilers. A solution would be to disable "autolink" (see your documentation for that: A quick google search showed the macro "BOOST_ALL_NO_LIB" to disable autolinking for ALL Boost librar...
2,458,917
2,458,941
Passing unknown classes to String Streams in C++
I am using a template function and I am passing and I may be sending instances of a variety of classes to a string stream. What can I do to make sure this continues to work? Let me be more specific where do I define the behavior for this? Is there some member that should be on each class being sent to the string stream...
It sounds to me like you want to make stream insertion operators. for a class you want to be able to output to a stream, define the free function: std::ostream& operator<<(std::ostream& stream, const SomeClassType& x) { stream << x.someData(); return stream; } So if we have SomeClassType z;, and we do std::co...
2,458,939
2,458,956
Compile redeclaration error of global variable in C++, but not in C
Suppose that I have those three files: a.h //a.h header #include <stdio.h> int int_variable; void a_f() { printf("int_variable: %d\n", int_variable) int_variable++; } b.h //b.h header #include <stdio.h> int int_variable; void b_f() { printf("int_variable: %d\n", int_variable) int_variable++; } main.c //...
In C, the two variables are actually combined into a single variable because neither is explicitly initialized. If you change both your h files to: // a.h int int_variable = 0; and: // b.h int int_variable = 0; you will get a redefinition error.
2,459,034
2,459,046
"Undefined Symbols" when inheriting from stdexcept classes
Here is an exception defined in <stdexcept>: class length_error : public logic_error { public: explicit length_error(const string& __arg); }; Here is my exception: #include <string> #include <stdexcept> using namespace std; class rpn_expression_error : public logic_error { public: explicit rpn_expression_er...
There is a problem with the way you are catching your exceptions. Specifically, consider this code: struct Base { virtual void do() { std::cout << "Base!" << std::endl; } }; struct Derived : Base { virtual void do() { std::cout << "Derived!" << std::endl; } }; void foo(Base x) { x.do(); } int main() { ...
2,459,057
2,459,101
Array length with pointers
How in C++ get array length with pointers only ? I know that tab name is pointer to first element, but what next ?
You cannot. A pointer is just a memory location, and contains nothing special that could determine the size. Since this is C++, what you can do is pass the array by reference like so: template <typename T, size_t N> void handle_array(T (&pX)[N]) { // the size is N pX[0] = /* blah */; // ... pX[N - 1] =...
2,459,550
2,459,558
How can I print a NUL character without a space in C?
I have a situation where I have to print out a NUL character if there is no action in a part of my program. Take for example the code below: char x = '\0'; ... printf("@%c@\n", x); I want it to print this: @@ but it prints out @ @ Whats the correct way not to have the \0 character printed out a space as above?
if (x == 0) printf("@@\n"); else printf("@%c@\n", x); It's not actually printing a space, it actually outputs the \0. It's just that whatever you're viewing the text with is displaying the \0 as a space.
2,459,588
2,483,454
Pass by reference in Boost::Python
Consider something like: struct Parameter { int a; Parameter(){a = 0;} void setA(int newA){a = newA;} }; struct MyClass { void changeParameter(Parameter &p){ p.setA(-1);} }; Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instanti...
Python doesn't have references, so when you pass reference to python boost::python calls copy-ctor of your object. In this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.
2,459,607
2,459,886
A quick design question about C++ container classes in shared memory
I am writing a simple wrapper around boost::interprocess's vector container to implement a ring buffer in shared memory (shm) for IPC. Assume that buf is an instance of RingBuffer created in shm. Now, in its ctor, buf itself allocates a private boost::interprocess::vector data member to store values, e.g. m_data. My qu...
boost::interprocess::vector takes an allocator type as a template parameter. This allocator needs to allocate from the shared memory (see the examples of use). If you class allocates memory with new, then that memory will only be accessible from the process it was allocated in. This is wrong, and is exactly why boost::...
2,459,755
2,459,782
Why can't we have an immutable version of operator[] for map
The following code works fine : std::map<int, int>& m = std::map<int, int>(); int i = m[0]; But not the following code : // error C2678: binary '[' : no operator... const std::map<int, int>& m = std::map<int, int>(); int i = m[0]; Most of the time, I prefer to make most of my stuff to become immutable, due to reason ...
operator[] will create the entry if it does not exist in the map. This is not possible if the operator is implemented for a const map. This is the explanation given in The C++ Programming Language: Subscripting a map adds a default element when the key is not found. Therefore, there is no version of operator[] ...
2,459,776
2,460,089
C++: type Length from float
This is kinda like my earlier question: C++: Vector3 type "wall"? Except, now, I want to do this to a builtin rather then a user created type. So I want a type "Length" that behaves just like float -- except I'm going to make it's constructor explicit, so I have to explicitly construct Length objects (rather than have ...
It sounds like you want to wrap a float primitive in your own class. Here's an example to get you started: class Length { protected: float value_; public: Length(float value) : value_(value) { } static Length operator +(Length a, Length b) { return Length(a.value_ + b.value_); } static Length operator -...
2,459,800
2,459,815
How can I break if gdb is attached, but continue if it is not?
I have some debugging code that if executed while running with GBD attached should break the execution of the application, but if GDB is not running it should continue. The code I'm working with looks something like this in structure: try { if( some_complex_expression ) { gdb_should_break_here(); do_some_...
Actually it looks like just making sure there is an empty gdb_should_break_here() function everywhere I need to break will work. (So long as I'm not optimising the code). Then all I need to do is a break gdb_should_break_here and gdb will stop in all the right places. Guess I overlooked it as my code wasn't really th...
2,459,809
2,461,694
Convert CString array to System::String
I want to convert CString array to managed code ot send it to C#. For normal CString i did like this, CString menu = "MENU"; String ^ msg = gcnew String(menu); Globals1::gwtoolbar->Add(msg); But now i want to send array of string.i dont know how to do for CString array. When i gave like this it shows error CString men...
Given: CString menu[10] To convert to a managed array of String: #DEFINE MENU_COUNT 10; array<String^>^ clrMenu = gcnew array<String^>(MENU_COUNT); for (int i = 0; i < MENU_COUNT; ++i) { clrMenu[i] = gcnew String(menu[i]); }
2,459,999
2,460,083
Planning a programming project by example (C# or C++)
I am in the last year of undergraduate degree and i am stumped by the lack of example in c++ and c# large project in my university. All the mini project and assignment are based on text based database, which is so inefficient, and console display and command, which is frustrating. I want to develop a complete prototype...
Before I start this is a shallow answer to a deep question. 1) It looks like you have a reasonable grasp of the major components of your target application. As a .net developer I'd build assemblies that matched broad areas of functionality (not sure what the equivalent is in PHP) and then you can use those assemblies t...
2,460,376
2,460,597
How might I assume a "default value" when parsing using boost::spirit?
Let's say I have a grammar defined to something like: some_rule := a b [c [d]] where c, and d are optional and default to a certain value (let's say 14) if not given. Can I get it to default to the 14 if the value isn't given? I want the produced std::vector to always be of size 4. The closest I've come is like the fo...
It looks like you can do this with the boost::qi::attr auxiliary parser. int default_value = 14; qi::rule<Iterator, int(), ascii::space_type> some_optional_rule; qi::rule<Iterator, std::vector<int>(), ascii::space_type> some_rule; some_optional_rule %= int_ | attr(default_value); some_rule %= re...
2,460,402
2,460,567
Tutorials for an experienced C# user to learn C++
Are there any good resources for learning C++ that a C# user could use, which don't require knowledge of C? I have quite a good knowledge of C# via courses in my University's game development program (in a 300 level course right now) but now I need to use C++ for a project. I would use a beginner tutorial but they ar...
There are lots of resources titled C# for C++ programmers. You can use them ;) You will come to know what are the things you are going to miss when you move from C# to C++. C++ vs. C# - a Checklist from a C++ Programmers Point of View. Learn some syntax first and then some STL. In a week you will feel comfortable. Bu...
2,460,417
2,460,439
How to partition bits in a bit array with less than linear time
This is an interview question I faced recently. Given an array of 1 and 0, find a way to partition the bits in place so that 0's are grouped together, and 1's are grouped together. It does not matter whether 1's are ahead of 0's or 0's are ahead of 1's. An example input is 101010101, and output is either 111110000 or ...
I don't see how there can be a solution faster than linear time. Imagine a bit array that is all 1's. Any solution will require examining every bit in this array before declaring that it is already partitioned. Examining every bit takes linear time.
2,460,537
2,460,628
Generating tuples from tuples
Say you have a tuple and want to generate a new tuple by applying a metafunction on each type of the first one. What' the most efficient C++ metafuntion to accomplish to this task? Is it also possible to use C++0x variadic template to provide a better implementation?
How 'bout this one: template<typename Metafun, typename Tuple> struct mod; // using a meta-function class template<typename Metafun, template<typename...> class Tuple, typename ...Types> struct mod<Metafun, Tuple<Types...>> { typedef Tuple<typename Metafun::template apply<Types>::type...> type; }; Then typedef ...
2,460,549
2,461,291
Deriving streambuf or basic_ostringstream?
I want to derive a stringstream so that I can use the operator<< to construct a message which will then be thrown. The API would look like: error("some text") << " more text " << 42 << std::endl; This should do a throw "some text more text 42" So what I did is make an errorbuf (inheriting from streambuf) which overlo...
I'll trot out my favourite macro again here: #define ATHROW( msg ) \ { \ std::ostringstream os; \ os << msg; ...
2,460,571
2,460,578
Cannot convert CString to BYTE array
I need to convert CString to BYTE array. I don't know why, but everything that I found in internet does not work :( For example, I have CString str = _T("string"); I've been trying so 1) BYTE *pbBuffer = (BYTE*)(LPCTSTR)str; 2) BYTE *pbBuffer = new BYTE[str.GetLength()+1]; memcpy(pbBuffer, (VOID*)(LPCTSTR)StrRegID, ...
Your CString is Unicode (two bytes per character) and you try to interpret it as ANSI (one byte per character). This leads to results you don't expect. Instead of casting the underlying buffer into char* you need to convert the data. Use WideCharToMultiByte() for that.
2,460,944
2,461,041
Window interface instead of console in c
I have console application in c. I want to convert into window application, kindly guide me so that I can make it possible.
Outline of steps you need to take: replace main with WinMain change subsystem from Console to Window create a main window or a dialog (resource editor may come handy here), and its corresponding procedure create a message loop change a structure of your program to be executed in a loop (the program should be always ...
2,460,953
2,461,212
Is there any simple way to determine when the popup menu was dismissed?
I'm displaying a popup menu using TrackPopupMenu and would like to know when it is dismissed via clicking outside of it. I've looked through all the menu functions but didn't find anything useful in this regard. Spy++ told me that no window message is sent in this case. So, is there an easy way to do it without install...
[edit] This is better. If you specify TPM_RETURNCMD in the uFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero. The menu loop is ended when ::TrackPopupMenu() retu...
2,461,111
2,462,783
Are the following two statements semantically same?
Are the following two statements semantically same? #1 person p("Rahul", 20); #2 person const &p = person("Rahul", 20); EDIT: Sorry, I meant to ask whether the following two are semantically same: #1 person const p("Rahul", 20); #2 person const &p = person("Rahul", 20);
They are not. However, the difference are affected only by the fact that the second case needs a copy constructor to be accessible in C++03 (even if the copy constructor call is not actually done) // works with #1 fails with #2 struct f1 { f1(string, int); private: f1(f1 const&); };
2,461,272
2,461,375
which is preferd use istrstream or strtol/strtod for reading number from string
I have to read number from string .which one is safe and preferred istrstream atoi/atof strtol/strto Please guide me.
Why use <iostream> instead of <cstdio> ? Increase type safety, reduce errors, allow extensibility, and provide inheritability. printf() is arguably not broken, and scanf() is perhaps livable despite being error prone, however both are limited with respect to what C++ I/O can do. C++ I/O (using << and >>) is, relative t...
2,461,559
2,462,184
Are L'A' and 'A' totally same?
When we write a program which supports both unicode and multibytes, we often use _T("some string") macro for strings. But, does a character also need to wrap this macro? Are L'A' and 'A' totally same? Don't we need to wrap _T('A') for a character?
If you write 'A', and that value gets converted to wchar_t, then on Microsoft compilers at least, it will have the same value as if you'd written L'A' or _T('A'). The same can't be said of string literals, since there is no useful conversion from const char* to const wchar_t*. I think this means it's rather less import...
2,461,630
2,461,676
Why this works (Templates, SFINAE). C++
referring to yesterday's post, this woke me up this morning. Why does this actually work? As long as the function test is concerned, this function has no body so how can it perform anything? I want to know why and how this works? I'm REALLY interested to see your answers. template<typename T> class IsClassT { priv...
I assume you are refering to the Yes enum? IsClassT<T>::test<T>(0)? sizeof does not actually evaluate its arguments. That's why code like the following is legal, even though you might expect it to bail out on you: int* p = 0; int sizeof_int = sizeof(*p); //oops, p is 0 :(
2,461,880
2,469,088
Writing a Makefile.am to invoke googletest unit tests
I am trying to add my first unit test to an existing Open Source project. Specifically, I added a new class, called audio_manager: src/audio/audio_manager.h src/audio/audio_manager.cc I created a src/test directory structure that mirrors the structure of the implementation files, and wrote my googletest unit tests: sr...
William's answer got me where I needed to go. Just for the sake of the community, here's what I ended up doing: I moved my tests back into the main directory structure and prepended test_, as per William's suggestions. I added a few lines to src/audio/Makefile.am to enable unit tests: # Unit tests noinst_PROGRAMS = te...
2,461,924
2,462,135
Debugging instance of another thread altering my data
I have a huge global array of structures. Some regions of the array are tied to individual threads and those threads can modify their regions of the array without having to use critical sections. But there is one special region of the array which all threads may have access to. The code that accesses these parts of the...
How about wrapping your data with a transparent mutexed class? Then you could apply additional lock state checking. class critical_section; template < class T > class element_wrapper { public: element_wrapper(const T& v) : val(v) {} element_wrapper() {} const element_wrapper& operator = (const T& v) { #if...
2,461,977
2,462,019
Issue compiling c++ in c++builder
I have written a C++ program for a University assignment. I used Netbeans 6.8 running on my Mac and the code runs smoothly, no warnings, errors or problems/bugs. However when compiling and running on a Windows computer using CodeGear RAD Studio 2009 (C++ Builder) am getting several errors. [BCC32 Error] main.cpp(51): E...
You need: #include <string> and it's: #include <windows.h> though I doubt you need it. The reason your code worked on one platform but not another is that on the first platform one of the other library headers was including <string> itself. This behaviour is not specified by the C++ Standard, so the only safe rule is...
2,462,233
2,462,301
Safe way for getting/finding a vertex in a graph with custom properties -> good programming practice?
I am writing a Graph-class using boost-graph-library. I use custom vertex and edge properties and a map to store/find the vertices/edges for a given property. I'm satisfied with how it works, so far. However, I have a small problem, where I'm not sure how to solve it "nicely". The class provides a method Vertex getVert...
I would either change this to: bool getVertex(Vertex& vertex, Vertexproperties v_prop); or have getVertex raise an exception if the vertex is not found.
2,462,624
2,462,665
How can I find out what the current charset is in C++?
How can I find out what the current charset is in C++? In a console application (WinXP) I am getting negative values for some characters (like äöüé) with (int)mystring[a] and this surprises me. I was expecting the values to be between 127 and 256. So is there something like GetCharset() or SetCharset() in c++?
It depends on how you look at the value you have at hand. char can be signed(e.g. on Windows), or unsigned like on some other systems. So, what you should do is to print the value as unsigned to get what you are asking for. C++ until now is char-set agnostic. For Windows console specifically, you can use: GetConsoleOut...
2,462,737
2,463,173
c++, object life-time of anonymous (unnamed) variables
In the following code, the object constructed in the last line of 'main()', seems to be destroyed before the end of the expression. The destructor is called before the '<<' is executed. Is this how it is supposed to be? #include <string> #include <sstream> #include <iostream> using std::string; using std::ostringstrea...
I believe the behavior that you are seeing is because of the rule that "anonymous temporaries cannot be passed into functions as non-const references" (well not really NOT, but have undefined behavior or different behavior on different compilers). Thus, it does go to the << operator at the last line, but it finds the m...
2,462,773
2,462,819
C++ copy-construct construct-and-assign question
Here is an extract from item 56 of the book "C++ Gotchas": It's not uncommon to see a simple initialization of a Y object written any of three different ways, as if they were equivalent. Y a( 1066 ); Y b = Y(1066); Y c = 1066; In point of fact, all three of these initializations will probably result in t...
The syntax X a = b; where a and b are of type X has always meant copy construction. Whatever variants, such as: X a = X(); are used, there is no assignment going on, and never has been. Construct and assign would be something like: X a; a = X();
2,462,795
2,475,567
Is UTC or local time used with time-based notifications?
I have a time in the future when I want a notification to occur and need to know if ::CeSetUserNotificationEx expects UTC or local time in the stStartTime field of the CE_NOTIFICATION_TRIGGER structure if the dwType field is set to CNT_TIME?
After actually testing ::CeSetUserNotificationEx with both UTC and local time input, I'm in the position of answering my own question: ::CeSetUserNotificationEx wants local time.
2,462,845
2,462,923
Implement abstract class as a local class? pros and cons
for some reason I'm thinking on implementing interface within a some function(method) as local class. Consider following: class A{ public: virtual void MethodToOverride() = 0; }; A * GetPtrToAImplementation(){ class B : public A { public: B(){} ~B(){} void MethodToOverride() { ...
You could define B in the unnamed namespace of the implementation file where you implement GetPtrToAImplementation(). A should have a virtual dtor. By the current C++ standard, you cannot use local classes as template arguments. (Which means you can't use them with the STL, for example.)
2,462,951
2,462,985
C++ equivalent of StringBuffer/StringBuilder?
Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#'s StringBuilder or Java's StringBuffer?
The C++ way would be to use std::stringstream or just plain string concatenations. C++ strings are mutable so the performance considerations of concatenation are less of a concern. with regards to formatting, you can do all the same formatting on a stream, but in a different way, similar to cout. or you can use a stron...
2,462,961
2,463,052
Using static mutex in a class
I have a class that I can have many instances of. Inside it creates and initializes some members from a 3rd party library (that use some global variables) and is not thread-safe. I thought about using static boost::mutex, that would be locked in my class constructor and destructor. Thus creating and destroying instance...
You have declared, but not defined your class static mutex. Just add the line boost::mutex MyClass::mx; to the cpp file with the implementation of MyClass.
2,462,964
2,463,050
When should a member function have a const qualifier and when shouldn't it?
About six years ago, a software engineer named Harri Porten wrote this article, asking the question, "When should a member function have a const qualifier and when shouldn't it?" I found it to be the best write-up I could find of the issue, which I've been wrestling with more recently and which I think is not well cove...
The article seems to cover a lot of basic ground, but the author still has a question about const and non-const overloads of functions returning pointers. Last line of the article is: Many will probably answer "It depends." but I'd like to ask "It depends on what?" To be absolutely precise, it depends whether the state...
2,463,112
2,463,289
Pointer to a C++ class member function as a global function's parameter?
I have got a problem with calling a global function, which takes a pointer to a function as a parameter. Here is the declaration of the global function: int lmdif ( minpack_func_mn fcn, void *p, int m, int n, double *x, double *fvec, double ftol) The "minpack_func_mn" symbol is a typedef for a pointer to ...
You need a non-member or static member function; a member function pointer can't be used in place of your function type because it requires an instance to call it on. If your function doesn't need access to a LT_Calibrator instance, then you can simply declare it static, or make it free function. Otherwise, it looks li...
2,463,113
2,463,384
g++ C++0x enum class Compiler Warnings
I've been refactoring my horrible mess of C++ type-safe psuedo-enums to the new C++0x type-safe enums because they're way more readable. Anyway, I use them in exported classes, so I explicitly mark them to be exported: enum class __attribute__((visibility("default"))) MyEnum : unsigned int { One = 1, Two = 2 ...
You can pass the -Wno-attributes flag to turn the warning off. (It's probably a bug in gcc?)
2,463,198
2,463,250
printing stl containers with gdb 7.0
I have installed GDB 7.0 and python per the following instructions. In the same manual, there is a mention of this file stl-views-1.0.3.gdb. What confuses me is where it should be placed in order to enable pretty printing of stl containers. Would someone also explain to me all of this work? Thanks
in the gdb: source {full_path}stl-views-1.0.3.gdb now you'll have new commands, such as pvector, plist, pmap and more (replace {full_path} with the full path to the file. You can also put the command source stl-views-1.0.3.gdb in ~/.gdbinit - and then you'll have it automatically every time you launch gdb.
2,463,473
2,463,493
Why am I getting an error converting a ‘float**’ to ‘const float**’?
I have a function that receives float** as an argument, and I tried to change it to take const float**. The compiler (g++) didn't like it and issued : invalid conversion from ‘float**’ to ‘const float**’ this makes no sense to me, I know (and verified) that I can pass char* to a function that takes const char*, so why ...
See Why am I getting an error converting a Foo** → const Foo**? Because converting Foo** → const Foo** would be invalid and dangerous ... The reason the conversion from Foo** → const Foo** is dangerous is that it would let you silently and accidentally modify a const Foo object without a cast The reference goes on t...
2,463,528
2,463,548
How would I use for_each to delete every value in an STL map?
Suppose I have a STL map where the values are pointers, and I want to delete them all. How would I represent the following code, but making use of std::for_each? I'm happy for solutions to use Boost. for( stdext::hash_map<int, Foo *>::iterator ir = myMap.begin(); ir != myMap.end(); ++ir ) { delete ir->secon...
You have to make a function object: struct second_deleter { template <typename T> void operator()(const T& pX) const { delete pX.second; } }; std::for_each(myMap.begin(), myMap.end(), second_deleter()); If you're using boost, you could also use the lambda library: namespace bl = boost::lambda;...
2,463,697
2,463,824
Strange declaration(templates). C++
How can I understand what is declared here: (this is taken from another post on this forum) template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1]; Here's how I read: template of static function f called with (ChT<int Fallback::*, &C::x>*), but then I can't make sense why is there an address-of operato...
It's important to see return type. So, return type of this function is reference to char[1]; Imagine that f returns something like reference to the following: char ret[1]; For example template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1] { static char xx[1] = {'F'}; return xx; }
2,463,760
2,463,832
C++ long long manipulation
Given 2 32bit ints iMSB and iLSB int iMSB = 12345678; // Most Significant Bits of file size in Bytes int iLSB = 87654321; // Least Significant Bits of file size in Bytes the long long form would be... // Always positive so use 31 bts long long full_size = ((long long)iMSB << 31); full_size += (long long)(iL...
You misunderstand how the operation works. Your computation should be: // Always use 32 bits long long full_size = ((long long)iMSB << 32); full_size += (unsigned long long)(iLSB); However, the combination of 12345678, 87654321 is not 1234567887654321; it's 53024283344601009. Then when you do long double f...
2,463,855
2,464,092
passing string literal to std::map::find(..)
I've got a std::map: std::map<std::string, std::string> I'm passing string literal to find method. Obviously, I can pass a string literal such as .find("blah"); However, I wanted to declare it upfront, instead of hardcoding the string, so I have couple of choices now: const std::string mystring = "blah"; const char m...
Advantages and disadvantatges: const std::string mystring = "blah"; This is pretty much the standard C++ way to deal with strings. You can do about anything you'd ever need to do with a string with this. The main disadvantage is that it is slower. There is a dynamic allocation in there. Also, if .find relies on char[] ...
2,463,917
2,463,990
C++: Most common way to talk to one application from the other one
In bare outlines, I've got an application which looks through the directories at startup and creates special files' index - after that it works like daemon. The other application creates such 'special' files and places them in some directory. What way of informing the first application about a new file (to index it) is...
Pipes would be one option: see Network Programming with Pipes and Remote Procedure Calls (Windows) or Creating Pipes in C (Unix). I haven't done this in a while but from my experience with RPC, DCOM, COM, .NET Remoting, and socket programming, I think pipes is the most straightforward and efficient option.
2,463,944
2,463,993
Is there any tool to standardize format of C++ code?
I'm looking for a tool that works on Windows to reformat some C++ code in my codebase. Essentially, I've got some code I wrote a while ago that I'd like to use, but it doesn't match the style I'm using in a more recent project. What's the best way to reformat C++ code in a standard manner? Billy3
In Visual Studio: Edit / Advanced / Format Document The format applied to the document will match the settings in: Tools / Options / Text Editor / C/C++ Visual Studio might not support all the formatting options you want applied to your document, in which case you'll need a separate tool (such as Paul Betts is suggesti...
2,463,982
2,464,025
How to pause a program for a few milliseconds?
How to pause a program for a few milliseconds using C++ managed code? I tried Sleep() but it didn't work when I included the winbase.h file, I got lots of compile errors! for(int i=0; i<10; i++) { simpleOpenGlControl1->MakeCurrent(); System::Threading::Thread::Sleep(100); theta_rotated += 2.0* 3.141592653/(...
System::Threading::Thread::Sleep() as mentioned in another answer. But let me warn you, it is not precise, and for small (milliseconds) Sleep is extremely imprecise. consider that your app run together with other apps and threads and they all want processor time.
2,463,994
2,559,574
Qt phonon video player example C++ or python
Does anyone have a working example of a video player built using Qt phonon? (in C++ ) See my related question here . I am unable to build one using Python.
A working example of a video player built using Qt phonon: Dragon Player And here you find the Mplayer created with Phonen too, including all the sources: Phonon MPlayer. You need to login, then you can browse the source code by clicking on "Source" and then "Browse". EDIT: Oh, and of course the Media Player Example i...
2,464,150
2,464,178
Operator + for matrices in C++
I suppose the naive implementation of a + operator for matrices (2D for instance) in C++ would be: class Matrix { Matrix operator+ (const Matrix & other) const { Matrix result; // fill result with *this.data plus other.data return result; } } so we could use it like Matrix a; Matrix b; Matrix c...
The C++ standard gives permission for the compiler to elide the unnecessary copy in this case (it's called the "named return value optimization", usually abbreviated to NRVO). There's a matching "RVO" for when you return a temporary instead of a named variable. Nearly all reasonably recent C++ compilers implement both ...
2,464,296
2,464,405
Is it possible to defer member initialization to the constructor body?
I have a class with an object as a member which doesn't have a default constructor. I'd like to initialize this member in the constructor, but it seems that in C++ I can't do that. Here is the class: #include <boost/asio.hpp> #include <boost/array.hpp> using boost::asio::ip::udp; template<class T> class udp_sock { ...
When you define a constructor, you have 2 ways to "initialize" attributes: the initializer list the constructor body If you do not explictly initialize one of the attributes in the initializer list, it is nonetheless initialized (by calling its default constructor) for you... So in essence: class Example { public: ...
2,464,458
2,465,358
C++ thread safety - exchange data between worker and controller
I still feel a bit unsafe about the topic and hope you folks can help me - For passing data (configuration or results) between a worker thread polling something and a controlling thread interested in the most recent data, I've ended up using more or less the following pattern repeatedly: Mutex m; tData * stage; ...
You don't need volatile here. Use volatile only if the value can change due to something outside of your program, such as if the variable represents a memory-mapped hardware register. The values here are only modified inside your program, so you can trust the compiler to know when it can and can't cache the values. I...
2,464,629
2,464,691
Possible to distribute or parallel process a sequential program?
In C++, I've written a mathematical program (for diffusion limited aggregation) where each new point calculated is dependent on all of the preceding points. Is it possible to have such a program work in a parallel or distributed manner to increase computing speed? If so, what type of modifications to the code would I n...
If your algorithm is fundamentally sequential, you can't make it fundamentally not that. What is the algorithm you are using? EDIT: Googling "diffusion limited aggregation algorithm parallel" lead me here, with the following quote: DLA, on the other hand, has been shown [9,10] to belong to the class of inherently ...
2,464,664
2,464,713
An interview question on conditional operator
I recently encountered with this question: How to reduce this expression: s>73?61:60;. The hint given was that Instead of using conditional operator we could use a simple comparison which will work fine. I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself. EDIT...
Just like the other answers: s -= (s > 73) + 60; This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6: Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relati...
2,464,675
2,464,717
How do you process a large data file with size such as 10G?
I found this open question online. How do you process a large data file with size such as 10G? This should be an interview question. Is there a systematic way to answer this type of question?
If you're interested you should check out Hadoop and MapReduce which are created with big (BIG) datasets in mind. Otherwise chunking or streaming the data is a good way to reduce the size in memory.
2,464,826
2,465,576
screenshots of covered/minimized windows
I have the following code to take screenshots of a window: HDC WinDC; HDC CopyDC; HBITMAP hBitmap; RECT rt; GetClientRect (hwnd, &rt); WinDC = GetDC (hwnd); CopyDC = CreateCompatibleDC (WinDC); hBitmap = CreateCompatibleBitmap (WinDC, rt.right - rt.left, //width rt.bottom - rt.top);//height SelectObject (CopyDC, h...
No, a screenshot is exactly what it sounds like. You'll read the pixels out of the video adapter, what you get is what you see. You'll have to restore the window and bring it to the foreground to get the full view. WM_SYSCOMMAND+SC_RESTORE and SetForegroundWindow() respectively. Plus some time to allow the app to r...
2,464,838
2,466,594
An "About" message box for a GUI with Qt
QMessageBox::about( this, "About Application", "<h4>Application is a one-paragraph blurb</h4>\n\n" "Copyright 1991-2003 Such-and-such. " "For technical support, call 1234-56789 or see\n" "<a href=\"http://www.such-and-such.com\">http://www.such-and-such.com</a>" ); This code is creating the About message box w...
I think you should create a custom QWidget for your about widget. By this way, you can put on the widget all you want. By example, you can place QLabel using the openExternalLinks property for clickable link. To display a custom image on the QWidget, this example may help.
2,465,072
2,465,214
Bitmap manipulation in C++ on Windows
I have myself a handle to a bitmap, in C++, on Windows: HBITMAP hBitmap; On this image I want to do some Image Recognition, pattern analysis, that sort of thing. In my studies at University, I have done this in Matlab, it is quite easy to get at the individual pixels based on their position, but I have no idea how to ...
You can use OpenCV library as a full image processing tool. You can also use MFC's CImage or VCL's TBitmap just to extract pixel values from HBITMAP.
2,465,345
2,465,379
Get current time crossplatform in c++
How can I get current time (I need hours, minutes, seconds) crossplatform in c++? I saw here make structure of values but there are a lots of another stuff that I don't need. And memory is very important here.
The routines in <time.h> are cross-platform and in fact required to be available for conforming implementations of ISO C. Use time to retrieve the elapsed time since 1970, and localtime or gmtime to break that down into hours, minutes, and seconds, as needed. You shouldn't be concerned that struct tm uses too much mem...
2,465,378
2,465,464
How expensive is CreateThread()?
I'm just wondering exactly what factors affect how quickly createthread executes, and how long it has to live to make it "worth it". CONTEXT: Where in my game's loops should I spawn threads?
The main game loop is not the place to spawn worker threads. The main game loop should be as free of clutter as possible. Worker threads should be spawned during program startup and then used as need by the main game loop. Look into thread pooling techniques.
2,465,413
2,465,449
Qt - add a hyperlink to a dialog
Is there a way to add a clickable hyperlink in a Qt Dialog? I.e. it should look like a hyperlink (blue text), and when you click on it, it should open the hyperlink in the browser. Something like that:
Use QLabel::setOpenExternalLinks(bool), and set text on label <a href="yourlink">link text</a>.
2,465,512
2,465,566
In C++, where are static, dynamic and local variables stored? How about in C and Java?
In C++, where are static, dynamic and local variables stored? How about in C and Java?
If you're compiling C/C++ to create a windows executable (or maybe for any x86 system) then static and global variables are usually stored in a segment of the memory called a data segment. This memory is usually also divided to variables which are initialized and those that are not initialized by the program in their d...
2,465,546
2,465,631
Where do I put constant strings in C++: static class members or anonymous namespaces?
I need to define some constant strings that will be used only by one class. It looks like I have three options: Embed the strings directly into locations where they are used. Define them as private static constant members of the class: //A.h class A { private: static const std::string f1; static const ...
I'd place them in anonymous namespace in the CPP file. It makes them private to the implementation and at the same moment makes it visible to the non-member functions that are part of implementation (such as operator<<).
2,465,708
2,465,755
Is it possible to create a null function that will not produce warnings?
I have a logger in a c++ application that uses defines as follows: #define FINEST(...) Logger::Log(FINEST, _FILE, __LINE, __func, __VA_ARGS_) However what I would like to do is to be able to switch off these logs since they have a serious performance impact on my system. And, it's not sufficient to simply have my Log...
You could define an empty function with unnamed parameters: void nullFunc(int, int, int, const char*, ...) { } Then redefine your macro to call this function: #define FINEST(...) nullFunc(FINEST, _FILE, __LINE, __func, __VA_ARGS_)
2,465,738
2,465,823
C++ Long switch statement or look up with a map?
In my C++ application, I have some values that act as codes to represent other values. To translate the codes, I've been debating between using a switch statement or an stl map. The switch would look something like this: int code; int value; switch(code) { case 1: value = 10; break; case 2: value = 15; ...
Personally, I would use the map, as its use implies a data lookup - using a switch usually indicates a difference in program behavior. Furthermore modifying the data mapping is easier with a map than with a switch. If performance is a real issue, profiling is the only way to get a usable answer. A switch may not be fas...
2,465,751
2,465,803
How to return a 'read-only' copy of a vector
I have a class which has a private attribute vector rectVec; class A { private: vector<Rect> rectVec; }; My question is how can I return a 'read-only' copy of my Vector? I am thinking of doing this: class A { public: const vect<Rect>& getRectVec() { return rectVect; } } Is that the right way? I am thinking this...
That is the right way, although you'll probably want to make the function const as well. class A { public: const vect<Rect>& getRectVec() const { return rectVect; } }; This makes it so that people can call getRectVec using a const A object.
2,465,845
5,316,835
Eclipse CDT Error Parser for external gcc-based builder
I understand that CDT 7 will have a regular expression error parser included, but I'm using CDT 6 now. I have an external CDT builder which just calls a shell script to trigger my build, (Jam-based). The build uses GCC, and the errors and warnings are streamed to a Console view, but of course no error parser is lookin...
I'm not sure if this question is still actual, but the following solution should work to populate Problems view: 1) Create an empty C++ makefile in CDT (let's call it solution1) 2) From the project's context menu (in Project Explorer) select "Import..." 3) In the "Import" wizard select "General/File System", click "Nex...
2,465,964
2,466,932
Are there any C++ tools that detect misuse of static_cast, dynamic_cast, and reinterpret_cast?
The answers to the following question describe the recommended usage of static_cast, dynamic_cast, and reinterpret_cast in C++: When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? Do you know of any tools that can be used to detect misuse of these kinds of cast? Would a static analysis tool ...
Given that there is no reliable way of telling what type the pointer points to at compile time, this is a pretty hard problem to catch at compile time. The simplest method is to do the catch at run-time, using a macro "safe_cast" which compiles to a dynamic_cast with an assert in debug, and a static_cast in release. No...
2,465,983
2,469,249
Devising a test strategy
As part of a new job, I have to devise and implement a complete test strategy for the company's new product. So far, all I really know about it is that it is written in C++, uses an SQL database and has a web API which is used by a browser client written using GWT. As far as I know, there isn't much of an existing stra...
Testing Computer Software is a great soup-to-nuts book on the entire testing process. In addition to the items you mentioned, you'll need to think about other types of testing (performance, security, localization, stress testing, to name a few) and how to manage the test process; test plans, issue tracking, test data, ...
2,466,028
2,466,290
two static libraries
I am currently providing a static library using vs2008. I am in the process of building my static library. However, since I am using another static library is there a way that i package this as a single static library. The reason here is that they will be calling functions in my library that depend on that other static...
Here is one way: Find out all the object files in the static library. That can be done by running the command lib STATICLIB /list Extract each object listed. You must give the exact name from step 1 (lib STATICLIB /extract:.\debug\foo.obj) You can then add all the objects extracted form step 2 into your library
2,466,131
2,466,156
Is re-throwing an exception legal in a nested 'try'?
Is the following well-defined in C++, or not? I am forced to 'convert' exceptions to return codes (the API in question is used by many C users, so I need to make sure all C++ exceptions are caught & handled before control is returned to the caller). enum ErrorCode {…}; ErrorCode dispatcher() { try { throw; ...
That's fine. The exception is active until it's caught, where it becomes inactive. But it lives until the scope of the handler ends. From the standard, emphasis mine: §15.1/4: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. The temporary...
2,466,318
2,590,826
Vista Basic theme ribbon issue
Under Vista, when in Basic theme, after calling IUIFramework::Destroy() the Vista theme is lost, and enlarging the window does not display outside of the initial area. You can repro it easily with the SimpleRibbon SDK sample. In simpleribbon.cpp, insert in the WndProc switch block: case WM_KEYUP: DestroyFramework();...
The ribbon control seems to set a window region and forget to remove it at ribbon destruction. Setting a null window region on return of IUIFramework::Destroy() seems to solve the problem .
2,466,337
2,467,412
C++Builder compile issue
This is a follow-up question to this question I asked earlier. Btw thanks Neil Butterworth for your help Issue compiling c++ in c++builder A quick recap. I'm currently developing a C++ program for university, I used Netbeans 6.8 on my personal computer (Mac) and it all works perfect. When I try them on my windows part...
I am assuming that you have debugging enabled, and you can't even step into main() with the debugger (Pressing [F7] or [F8]), like the program is crashing before it even gets into main. This could be a problem if you have a global (or static) instance of an object, and the object's constructor code is crashing. If y...
2,466,342
2,466,441
C++ DLL creation for C# project - No functions exported
I am working on a project that requires some image processing. The front end of the program is C# (cause the guys thought it is a lot simpler to make the UI in it). However, as the image processing part needs a lot of CPU juice I am making this part in C++. The idea is to link it to the C# project and just call a func...
It seems you are confused about which files to include in your DLL project vs your console project. If it is true that "The console project holds all the files" then this is your problem. Your DLL project needs to include the cpp file which has the __declspec(dllexport)s. As you describe it, you have included your RefP...
2,466,486
2,466,549
C++ union assignment, is there a good way to do this?
I am working on a project with a library and I must work with unions. Specifically I am working with SDL and the SDL_Event union. I need to make copies of the SDL_Events, and I could find no good information on overloading assignment operators with unions. Provided that I can overload the assignment operator, should I ...
In a union, the elements all occupy the same memory, like they sit on top of each other. If you write to another element of a union, it overwrites the others. As such, copying element by element is a waste of time. You could copy the largest element only, but then you would have to know which one that is (not every...
2,466,507
2,466,542
Using free function as pseudo-constructors to exploit template parameter deduction
Is it a common pattern/idiom to use free functions as pseudo-constructors to avoid having to explicitly specify template parameters? For example, everyone knows about std::make_pair, which uses its parameters to deduce the pair types: template <class A, class B> std::pair<A, B> make_pair(A a, B b) { return std::pair<...
Apparently it's called "Object Generator". See "More C++ Idioms" and "Boost" on this topic. I personally find it very useful and use it alot. Also, I think one might see expression templates as a special form of object generators, since all they do is construct complex types by means of operand types and data you norm...
2,466,622
2,466,657
What is better for a student programming in C++ to learn for writing GUI: C# vs QT?
I'm a teacher(instructor) of CS in the university. The course is based on Cormen and Knuth and students program algorithms in C++. But sometimes it is good to show how an algorithm works or just a result of task through GUI. Also in my opinion it's very imporant to be able to write full programs. They will have courses...
It is better to familiarize students with Qt, as Qt is actually C++. C# is a completely different beast, and if you use C#, you will very likely get your students confused about what things are Microsoft- or C#-specific vs. what is actually defined in the ISO C++ standard, whereas this will be more obvious with just C+...
2,467,000
2,467,184
Is there a Java Map keySet() equivalent for C++'s std::map?
Is there a Java Map keySet() equivalent for C++'s std::map? The Java keySet() method returns "a set view of the keys contained in this map."
Perhaps the following might be of use: #include <iostream> #include <iterator> #include <algorithm> #include <map> #include <set> #include <string> template< class Key, class T, class Comparator, class MapAllocator, class SetAllocator> void make_key_set(const std::map<Key,T,Co...
2,467,332
2,469,057
How to debug a running C++ program in Linux?
I have a question about debugging a running C++ program in Linux. If a programming is already running and can't be interrupted, how to do that. I can find three ways, but I don't know too much about details, I am grateful if any one can elaborate it deeper. 1) we can use GDB by specifying the process ID gdb -p PID In...
I can't find -p option in gdb man or their documentation, but it does work! I've tried it many times with older versions on RedHat and 7.0.1 on Debian. I'm not sure how exactly it finds the exe by PID (maybe /proc/<PID>/exe), but it does. Since it's not described in their documentation, perhaps it not the most recommen...
2,467,336
2,467,496
What is a good CPU/PC setup to speed up intensive C++/templates compilation?
I currently have a machine with an Opteron 275 (2.2Ghz), which is a dual core CPU, and 4GB of RAM, along with a very fast hard drive. I find that when compiling even somewhat simple projects that use C++ templates (think boost, etc.), my compile times can take quite a while (minutes for small things, much longer for bi...
Compile time problems with templates are often link problems, rather than compilation problems. Using templates internally in your .cpp files, but making sure that the headers don't actually include the template, is a good way to fix those. That can be done by either forward declaring the class, or wrapping your imple...
2,467,353
2,467,373
Memory efficient way to remove duplicate lines in a text file using C++
What is the most memory efficient way to remove duplicate lines in a large text file using C++? Let me clarify, I'm not asking for code, just the best method. The duplicate lines are not guaranteed to be adjacent. I realize that an approach optimized for minimal memory usage would result in slower speeds however this...
i would hash each line and then seek back to lines that have non-unique hashes and compare them individually (or in a buffered fashion). this would work well on files with a relatively low occurence of duplicates. When you use a hash, you can set the memory used to a constant amount (i.e., you could have a tiny hash ta...
2,467,384
2,467,411
What type can hold member-function-pointers of difference classes in C++?
I need an array to hold member-function-pointers of different classes. How can I define the array? The code should look like this: arr[0] = &CMyClass::FuncX; arr[1] = &CYourClass::FuncY; arr[2] = &CHerClass::FuncZ; I tried void*, but it doesn't work.
You can't; they are all different types and arrays are homogeneous. Regardless what the arguments are or what the return value is, there is an implicit this which is unique to the class type. The type of a class member pointer is: return_value (class_type::*)(parameters); As you can see, because they belong to differe...
2,467,413
2,467,426
Sort CMap Key by String Length
Previously, I am using STL map to perform the mentioned task. struct ltstr { bool operator()(std::string s1, std::string s2) const { const int l1 = s1.length(); const int l2 = s2.length(); if (l1 == l2) { // In alphabetical order. return s1.compare(s2) < 0; } //...
You cannot. From the MSDN documentation for CMap: You might think that this iteration is sequential by key value; it is not. The sequence of retrieved elements is indeterminate.
2,467,568
2,467,626
How can I change the precision of printing with the stl?
I want to print numbers to a file using the stl with the number of decimal places, rather than overall precision. So, if I do this: int precision = 16; std::vector<double> thePoint(3); thePoint[0] = 86.3671436; thePoint[1] = -334.8866574; thePoint[2] = 24.2814; ofstream file1(tempFileName, ios::trunc); file1 << std::s...
Use std::fixed , this should work for you. file1 << std::fixed << std::setprecision(precision) << thePoint[0] << "\\" << thePoint[1] << "\\" << thePoint[2] << "\\";
2,467,608
2,474,374
TeeChart VCL vs .NET
Is TeeChart .NET built from the same source as TeeChart VCL? I'm just wandering as we have a VCL application heavily dependent on TeeChart and I would like to redevelop the GUI component in .NET so I can switch from the Codegear IDE to Visual Studio.
The .NET Framework and VCL are two very, very different libraries. The different versions of TeeChart would not be built on the same source, although they likely will have very similar APIs.
2,467,625
2,467,683
How can I eliminate an element in a vector if a condition is met
I have a vector of Rect: vector<Rect> myRecVec; I would like to remove the ones which are overlapping in the vector: So I have 2 nested loop like this: vector<Rect>::iterator iter1 = myRecVec.begin(); vector<Rect>::iterator iter2 = myRecVec.begin(); while( iter1 != myRecVec.end() ) { Rectangle r1 = *iter1; wh...
You need to increment iter1 and iter2. erase returns an iterator to the next element. When you delete, use this instead of incrementing the iterator. Like so: while( iter1 != myRecVec.end() ) { Rectangle r1 = *iter1; iter2 = iter1 + 1; while( iter2 != myRecVec.end() ) { Rectangle r2 = *iter2; ...
2,467,690
2,467,692
Is there any c++ class that can't be used in STL?
Just come up with this question. Any hint?
classes that can't be copied. STL containers require objects to be copyable since the container owns a copy of that object, and needs to be able to move it around.
2,467,807
2,467,826
C/C++ for Core Logic Development of a Web Application?
Can C/C++ be choice of keeping all your logic (business/domain) for web application? Why? I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript. We like to utilize our free time to work on our some good ideas we developed together. The ideas require knowledg...
C/C++ and Python can be integrated fairly easily, but Python really should be a snap for anyone that knows C well to pick up in a week.
2,468,122
2,468,139
Why can't a std::vector take a local type?
void foo() { struct Foo { .. }; std::vector<Foo> vec; // why is this illegal? } I'm not returning Foo to the outside world. It's just a temporary type that I use within the function.
A local class can't be a template argument. Because the standard says:- 14.3.1 paragraph 2: "A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template argument for a template type parameter." [Example: template <class T> class X { /* ... */ }; voi...
2,468,152
2,468,168
Size of a class with 'this' pointer
The size of a class with no data members is returned as 1 byte, even though there is an implicit 'this' pointer declared. Shouldn't the size returned be 4 bytes(on a 32 bit machine)? I came across articles which indicated that 'this' pointer is not counted for calculating the size of the object. But I am unable to unde...
The this pointer is not a member of the class. It's just a construct that is used in methods belonging to the class to refer to the current instance. If you have a class like this: class IntPair { public: IntPair(int a, int b) : _a(a), _b(b) { } int sum() const { return _a + _b; } public: int _a; int _b; }; ...
2,468,161
2,496,393
How to reliably replace a library-defined error handler with my own?
On certain error cases ATL invokes AtlThrow() which is implemented as ATL::AtlThrowImpl() which in turn throws CAtlException. The latter is not very good - CAtlException is not even derived from std::exception and also we use our own exceptions hierarchy and now we will have to catch CAtlException separately here and t...
I encountered similar problems when writing my own memory manager and wanted to overrule malloc and free. The problem is that ATL::AtlThrowImpl is probably part of a source file that also includes other files that are really needed. If the linker sees a reference to a function in one of the object files, it pulls in th...
2,468,203
2,468,254
How can I make `new[]` default-initialize the array of primitive types?
Every now and then I need to call new[] for built-in types (usually char). The result is an array with uninitialized values and I have to use memset() or std::fill() to initialize the elements. How do I make new[] default-initialize the elements?
int* p = new int[10]() should do. However, as Michael points out, using std::vector would be better.
2,468,367
2,468,538
Is new int[10]() valid c++?
While trying to answer this question I found that the code int* p = new int[10](); compiles fine with VC9 compiler and initializes the integers to 0. So my questions are: First of all is this valid C++ or is it a microsoft extension? Is it guaranteed to initialize all the elements of the array? Also, is there any diff...
First of all is this valid C++ or is it a microsoft extension? It is valid in C++, the relevant part of the standard is 5.3.4, with the first paragraph containing the grammar Is it guaranteed to initialize all the elements of the array? Yes. Paragraph 5.3.4/15 states that A new-expression that creates an object of ty...
2,468,792
2,621,627
Flushing a boost::iostreams::zlib_compressor. How to obtain a "sync flush"?
Is there some magic required to obtain a "zlib sync flush" when using boost::iostreams::zlib_compressor ? Just invoking flush on the filter, or strict_sync on a filtering_ostream containing it doesn't see to do the job (ie I want the compressor to flush enough that the decompressor can recover all the bytes consumed b...
It turns out there is a fundamental problem that the symmetric_filter that zlib_compressor inherits from isn't itself flushable (which seems rather an oversight). Possibly adding such support to symmetric_filter would be as simple as adding the flushable_tag and exposing the existing private flush methods, but for no...