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 |
|---|---|---|---|---|
4,314,291 | 4,314,343 | c++ save and load game with pointers in structs | I know I can use:
MyGame game; // the game object
//
ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?
and: how to solve this?
| You can't just write pointers to a stream and expect it to be magically done. You need to implement save/load methods in your objects. E.g:
class Serializable
{
virtual void save(std::ofstream& _out) const = 0;
virtual void load(std::ifstream& _in) = 0;
}; // eo class Serializable
// some game object
class ... |
4,314,462 | 4,314,559 | Timer in VC++ for Non-GUI Applications | I want to test a code which is designed for running on a Microcontroller and it is platform independent.
Problem is I currently don't have any Embedded simulator (due to some damn reason!) and I want to test it... I am using Visual Studio 2008 (What a Pity!!).... Code is entirely in C but as VS 2008 doesn't support C, ... | For high precision timers the your best bet is probably CreateTimerQueueTimer (not used personally).
Personally I used to use timeSetEvent but that was way back years and years ago.
|
4,314,464 | 4,314,510 | C++ - Splitting Filename and File Extension | Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:
void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
std::string ea;
std::stringstrea... | I think you could use std::string find_last_of to get the index of the last ., and substr to cut the string (although the "complex extensions" involving multiple dots will require additional work).
|
4,314,714 | 4,314,773 | Performance of a trimming function | My old Trimming function:
string TailTrimString (const string & sSource, const char *chars) {
size_t End = sSource.find_last_not_of(chars);
if (End == string::npos) {
// only "*chars"
return "";
}
if (End == sSource.size() - 1) {
// noting to trim
return sSource;
}
return sSource.substr(0, E... |
it possible that boost's implementation works slower than my quite straightforward implementation?
Of course.
Is there anything I should use instead of is_any_of in order to improve the performance?
Yeah -- your original code. You said nothing about it having a defect, or the reason why you re-implemented it usin... |
4,314,990 | 4,315,551 | Anything wrong with this design to initialize the array in the DLL? | Lets assume we've got a DLL and there should be an array stored globally in it that's going to be exported, the thing is we want to initialize it by reading some content from a file, so personally I find myself no other way than putting it in a struct to be able to initialize using constructor:
struct Construction{
pu... | Yes, you've set yourself up for a very nasty surprise at some point.
Global object constructors run during the startup of the C runtime for the DLL.
The C runtime startup code runs during DLLMain.
During DLLMain, you are holding the DLL loader lock.
Your object constructor may involve calls to Win32 api's that load o... |
4,315,140 | 4,315,165 | Converting function signature from compiler language to c++ | Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:
int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")
Turns into:
.text._ZN7funcsns3fooEidRNS_4TempE
(You might know it from the "undefined symbol" and some other linking errors that pr... | On a system using the GNU toolchain, the c++filt program does exactly what you're looking for. It's part of the "binutils" package. Dunno about other systems.
The ".text." isn't part of the mangled name. Running c++filt _ZN7funcsns3fooEidRNS_4TempE yields funcsns::foo(int, double, funcsns::Temp&).
|
4,315,214 | 4,315,379 | How to learn to write idiomatic c++ code | I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually consider... | You might wnat to check out The Definitive C++ Book Guide and List
For your purposes I would especially recommend:
C++ Coding Standards
Effective STL
Beyond the C++ Standard Library: An Introduction to Boost
Code Complete
Clean Code (Examples in Java, still valid though.)
They are not in particular order, also you mi... |
4,315,513 | 4,315,525 | Returning an Array from a C++ Function |
Possible Duplicate:
howto return a array in a c++ method?
How can an array be returned from a function? I'm going for an effect like this:
int getArray()
{
return {1, 2, 3, 4, 5};
}
...
int myArray[5] = getArray();
| Either dynamic allocation or std::vector. You can't return an array by value.
|
4,315,602 | 4,315,726 | How can I get vc++ and g++ to behave the same regarding typename for dependent qualified types? | Is there a switch I can supply to cl.exe that will enable a warning or error when a typename is missing from a qualified dependent type?
I'm working in an environment where developers tend to work one one platform, either Windows or Linux, and the code is ultimately built on both platforms nightly. We've encountered a... | There is no check like this in Visual Studio 2005 or 2008. The reason behind this is the compiler internals (the way templates are processed) are different between VS and GCC, and VS does much less processing until templates are instantiated. Pretty much everything seems to be explained in the question you have linked.... |
4,315,625 | 4,315,703 | C++ - removal of a node in an AVL Tree | I'm currently trying to implement an AVL tree in C++, so far I've done pretty much everything except a node removal.
1) Can someone confirm that my algorithm for removing a node is correct?
Find the node to delete in the tree
if the node has 0 child : delete the node
else, if the node has 1 child: delete the node, and... | If the node was created using 'new' than it needs to be explicitly deleted, absolutely. They question will be where. If you are deleting the node, (the assumption is nobody else needs the contents of the node) then you should also delete the node itself after completing the nodes removal from the tree.
Now, the re... |
4,315,719 | 4,315,767 | Application Crashes on Thread Exit - C++ | My application is crashing when it exits the thread function. This is how my thread is initialized:
LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);
// Create the exit notify window thread event handle.
_hNotifyWindowT... | I might be wrong, but it seems like you're trying to create a window from a worker thread. Don't do this. Windows need the message pump in order to function, and there's only one message pump in your application -- it's in the main thread.
|
4,315,828 | 4,315,841 | Omitting the datatype (e.g. "unsigned" instead of "unsigned int") | I know that if the data type declaration is omitted in C/C++ code in such way: unsigned test=5;, the compiler automatically makes this variable an int (an unsigned int in this case). I've heard that it's a C standard and it will work in all compilers.
But I've also heard that doing this is considered a bad practice.
Wh... | unsigned is a data type! And it happens to alias to unsigned int.
When you’re writing unsigned x; you are not omitting any data type.
This is completely different from “default int” which exists in C (but not in C++!) where you really omit the type on a declaration and C automatically infers that type to be int.
As for... |
4,315,862 | 4,315,919 | Compiler error C3493: 'func' cannot be implicitly captured because no default capture mode has been specified | Can you help me resolve this compiler error?
template<class T>
static void ComputeGenericDropCount(function<void(Npc *, int)> func)
{
T::ForEach([](T *what) {
Npc *npc = Npc::Find(what->sourceId);
if(npc)
func(npc, what->itemCount); // <<<<<<< ERROR HERE
// Error 1 erro... | You need to specify how to capture func into the lambda.
[] don't capture anything
[&] capture-by-reference
[=] capture-by-value (copy)
T::ForEach([&](T *what) {
I'd also recommend that you should send func by const reference.
static void ComputeGenericDropCount(const function<void(Npc *, int)>& func)
|
4,315,969 | 4,316,020 | Where to define C++ class member template function and functors that instantiate it? | I have a class Foo which is used in a small standalone project. It has a class definition in Foo.h with the implementation for the class' member functions in an implementation file Foo.cpp.
First question - one of the member functions of class Foo is a template method Foo::doSomething(), is it correct that the implemen... | General rule:
If foo::doSomething() is used outside foo.cpp (i.e. if it's public or protected, usually), it must go in the header.
If not, putting in in the cpp file is perfectly ok, and even a good idea (as it keeps the clutter away from the header file).
So, if the functors are only used in the cpp file, by all mea... |
4,316,111 | 4,619,193 | "Unlimited" CEdit text without ES_AutoHScroll | I'm having undesirable reflexes with ES_AUTOHSCROLL Set.
What I'm trying to do is create an Edit that resizes with the text in it. However I hit a problem whenever the user types past the end of the edit.
Without ES_AUTOHSCROLL the user cannot type past the current size of the edit, so my edit doesn't grow to fit the ... | I found a way to simulate the effect I want.
I use ES_AUTOHSCROLL.
I respond to OnUpdate and change the size of the control to fit the text it contains. To handle the scrolling problem (it scrolls to insert text before it knows it will get bigger), still inside OnUpdate, I select 0,0, then return the previous selection... |
4,316,133 | 4,316,166 | How to check if C++ abstract method is defined at runtime | How to check if C++ abstract method is defined at runtime
class ABase{
public:
virtual void do1() = 0;
};
class BBase: public ABase{
public:
virtual void do1(){}
};
class CBase: public ABase{
public:
};
ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
base->do1();
This gives error.
T... | As you can't instantiate an abstract class, any class you encounter at runtime will not have any pure virtual methods (unless you're in a constructor or destructor at the time), they'll all have been overriden with a non-pure overrider. There is nothing to check.
|
4,316,147 | 4,316,313 | Modifying assembly instructions before loading | I have a DLL that I need to load (I have written it and compiled it), and I would like to insert instructions between existing instructions of the assembly code before loading the DLL into memory. Of course, you can't just read every byte and insert them between there because instructions sometimes are multiple bytes. ... | You have (at least) two choices:
open the DLL file and modify it using file read/write operations
load the DLL and modify the instructions before they execute
Both are possible, though with the latter it will be necessary to circumvent or disable security protection: code (as opposed to data) is loaded into memory w... |
4,316,202 | 4,542,102 | problem with poco on snow leopard + eclipse | hey, i'm trying to work with poco on osx snow leopard, compiling via eclipse with the 64bit mac parser,
when trying to compile a simple code using Poco DateTime i get the following error :
"Poco::DateTime::DateTime()", referenced from:
_main in Run.o
"Poco::DateTime::~DateTime()", referenced from:
_main ... | the problem is that poco needs to be compiled for a 64bit environment in Snow leopard,
although i have ditched eclipse all together now and am using Xcode for c++, so much better.
|
4,316,316 | 4,316,376 | Constructor: is it the right one being called? | In your opinion, which constructor will be called?
class Element {
public:
Element(bool b = true, bool c = true);
Element(const std::string s, bool b = true, bool c = true);
};
...
Element element("something", true);
Wrong! The first one.
Do I have to restart Stroustrup's book from the beginning?
I tried witho... | There is a built-in conversion from pointer types to bool, non-null pointers are converted to true and null pointer values to false.
std::string is a user-defined type (in the loosest sense of the word user) so the conversion from const char* to std::string won't be preferred over the built-in const char* to bool conve... |
4,316,317 | 4,316,361 | C++ -& CRTP . Type erasure vs polymorphism | OK here we go. I'm trying to use the CRTP template in order to remove the need of polymorphism from my app. I use an aproach like the one bellow
template <RealType> class Base
{
void doSomething()
{
static_cast<RealType>(this)->doSomethingImpl()
}
class Derived1 : public Base
{
void doSomet... |
And my goal is mainly not to have a vtable.
If you want this, then, unless you implement your own virtual dispatch system (which would likely be inferior to what the compiler does), you're stuck with templates, a.k.a. compile-time polymorphism. And as the name says, in order to use this, everything must be known at ... |
4,316,442 | 6,296,808 | std::ofstream, check if file exists before writing | I am implementing file saving functionality within a Qt application using C++.
I am looking for a way to check to see if the selected file already exists before writing to it, so that I can prompt a warning to the user.
I am using an std::ofstream and I am not looking for a Boost solution.
| This is one of my favorite tuck-away functions I keep on hand for multiple uses.
#include <sys/stat.h>
// Function: fileExists
/**
* Check if a file exists
*
* @param[in] filename - the name of the file to check
*
* @return true if the file exists, else false
*/
bool fileExists(const std::string& filename)
{
... |
4,316,509 | 4,316,549 | Something wrong in c++ code | Please what wrong in this code:
#include <iostream>
#include <vector>
unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
*pChars = (char*)&container[0];
return container.size() * sizeof(int);
}
void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
int ... | You're copying the container when you pass it to ConvertToChars, then taking a pointer to one of its elements, then seeing the copy go out of scope, which invalidates your pointer.
|
4,316,592 | 4,316,678 | Porting a Visual C++ project to C# | I got my hands on some well documented C++ code that's about 1KLOC. It would take me a significant amount of time to port this line by line and debug the results, so I'm wondering if there are tools or ways to do it faster, and I have questions in case I have to do it fully manually.
Specific questions:
Does C# also ... | You might want to try this tool and see if that works out for you. There is a demo where you translate up to a 100 lines of code at a time:
http://tangiblesoftwaresolutions.com/Product_Details/CPlusPlus_to_CSharp_Converter_Details.html
Try it out and let us know. But it would prolly be more beneficial to port this yo... |
4,316,716 | 4,366,342 | Is it possible to use boost accumulators with vectors? | I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it's not possible to use the dumbest thing:
using namespace boost::accumulators;
//stuff...
accumulator_set<vector<double>, stats<tag::mean> > acc;
vector<double> some_vetor;
/... | I've looked into your question a bit, and it seems to me that Boost.Accumulators already provides support for std::vector. Here is what I could find in a section of the user's guide :
Another example where the Numeric
Operators Sub-Library is useful is
when a type does not define the
operator overloads required ... |
4,316,727 | 4,316,948 | Returning unique_ptr from functions | unique_ptr<T> does not allow copy construction, instead it supports move semantics. Yet, I can return a unique_ptr<T> from a function and assign the returned value to a variable.
#include <iostream>
#include <memory>
using namespace std;
unique_ptr<int> foo()
{
unique_ptr<int> p( new int(10) );
return p; ... |
is there some other clause in the language specification that this exploits?
Yes, see 12.8 §34 and §35:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...]
This elision of copy/move operations, called copy elision, is permitted [...]
in a return ... |
4,316,736 | 4,317,033 | using unallocated memory without error? | Why does that work?
#include <iostream>
using namespace std;
int main() {
float* tab[3];
int i = 0;
while(i < 3) {
tab[i] = new float[3-i];
i++;
}
cout << tab[2][7] << endl;
tab[2][7] = 6.87;
cout << tab[2][7] << endl;
i = 0;
while(i < 3)
delete[] tab[i];
... | Use of unallocated memory results in undefined behaviour. You can have no expectations of what will happen when you do this even on the same system and compiler, let alone across different combinations of hardware and compiler.
The program might crash immediately, it might work for a while and then fail later, it mi... |
4,316,749 | 4,341,980 | ClientDataSet CalcFields' odd trouble | I've got an odd and persistent problem... (Also my right shift key just stopped working, so please bear with my possibly odd caps & symbols; trying to get my fingers trained to use the left shift key is a pain.)
I'm running a CalcFields event when a ClientDataSet opens & goes through records (ie, AutoCalcFields is true... | why not use the DisplayFormat property? for example, in in a TClientDataSet.AfterOpen event do something like this:
dynamic_cast<TNumericField*>(DataSet->FieldByName("quantity_to_date_adjustment"))->DisplayFormat = "#,##0.00;(-#,##0.00)";
|
4,316,819 | 4,316,853 | How do I access individual words after splitting a string? | std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');
std::cout << token[0] << "\n";
This is printing individual letters. How do I get the complete words?
Updated to add:
I need to access them as words for doing something like this...
if (word[0] == "something")
do... | std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');
std::cout << token << "\n";
To store all the tokens:
std::vector<std::string> tokens;
while (getline(iss, token, ' '))
tokens.push_back(token);
or just:
std::vector<std::string> tokens;
while (iss >> token)
... |
4,316,952 | 4,824,467 | Retrieving Points of Polygons created by cvApproxPoly() | I have a CvSeq* containing the polygons created by running cvApproxPoly() on a CvSeq* created from running cvFindContors on a b&w input image. I want to access the CvPoints of each polygon returned from the CvSeq*. Code so far as follows (outlines is an IplImage containing the b&w input image):
//create pointers to s... | You can use cvGetSeqElem to iterate over the vertices of the polygon.
squares.c in samples/c has implemented this thing.
|
4,316,982 | 4,411,380 | gsoap databinding, how to access a sequence within the .h file generated by gsoap | I have no idea how to access FilenameType_sequence
class ns1__FilenameType
{
public:
// SEQUENCE OF ELEMENTS <xs:sequence minOccurs="1" maxOccurs="unbounded">
$int __size_FilenameType_sequence 1;
class __ns1__FilenameType_sequence
{
// std::string with le... | In case you're having the same problem as me the code is as follows
ns1__FilenameType_sequence * fnSeq = soap_new__ns1__FilenameType_sequence(soap, 2);
fnSeq[0].filename = "Becky";
fnSeq[1].filename = "Jen";
fnSeq[1].filename = "Cindy";
ns1__FilenameType->__size_FilenameType_sequence = 3;
ns1__FilenameType->__Filename... |
4,317,019 | 4,317,065 | C++ static pointer to function | I would like to have a private static pointer to a function in my class. Basically, it would look like this:
//file.h
class X {
private:
static int (*staticFunc)(const X&);
...
public:
void f();
};
//file.cpp
void X::f()
{
staticFunc(*this);
}
This gives me an "unresolved external symbol" error. I k... | //file.cpp
int (*X::staticFunc)(const X&);
void X::f()
{
staticFunc(*this);
}
|
4,317,103 | 4,317,367 | Can't find C++ 6.0 IDE in MSDN download area | I think this has something to do with a lawsuit with Sun over Java - but I can't verify this. I'm trying to get a legacy code base to compile 1st so I can begin upgrading it.
Also: I suppose I need to know where/how I CAN get the C++ 6.0 IDE install.
Digging through the "Pile of DVD's in the old developer's drawer" ri... | Yes, this was a result of the 2001 settlement between Microsoft and Sun over the Microsoft Java Virtual Machine. Several products were axed because of this, including Windows 98, Windows Me, Office 2000, Office XP, IE 5.5
Best place to find a license is at an auction site. It was always available at Ebay for example,... |
4,317,105 | 4,317,123 | Templated member function typedefs won't compile | #include <iostream>
#include <string>
using namespace std;
void printstr( const string & s ) { cout << s << endl; }
template < typename A >
class Test
{
public:
typedef void (*Func)( const A & );
};
typedef void (*Func)( const string & );
template < typename A >
void bind(
Test< A >::Func f, /... | The name Test<A>::Func is a dependent name and needs to be prefixed with typename
typename Test< A >::Func f,
For a more detailed explanation you should check out Johannes explanation in the following answer
Where and why do I have to put the "template" and "typename" keywords?
|
4,317,272 | 4,319,625 | Regex implementation with event driven matches? | This may sound a little odd, but it would be extremely useful to me. Are there any regex implementations (any language but preferably java, javascript, c, c++) that use an event based model for matches?
I would like to be able to register a bunch of different regular expressions I am looking for in a string via an eve... | This is very easy to do in Perl regular expressions. All you do is insert your event callouts at the appropriate point in the pattern in the most straightforward manner imaginable.
First, imagine a pattern for pulling out decimal numbers from string:
my $rx0 = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)/;
Let’s expand that out so ... |
4,317,315 | 4,317,509 | Why initializing data at global scope by passing it to some function is not possible? | I've been wondering for a while why initializing any data by passing it to some function is not permitted despite the fact that constructors that are a kind of function anyway can be called at global scope, so if we have something like an array at global scope it can't be initialized by any function but if it was in an... | Actually you can call functions at global scope.
int foo()
{
return 5;
}
int bar = foo();
It's just the way that C was designed years ago that you can't have functions run on their own at global scope. All program code starts at main.
In general, the less you depend on global initialization (avoid it if possible)... |
4,317,465 | 4,616,181 | How to find a functions address to hook/detour in an EXE file? | I drove against a wall again and need your help with some low-level stuff. I already succeeded in hooking exported DLL-Functions (with this code btw.) by injecting them into my target process (e.g. I can easily detour MessageBoxW from user32.dll). Unfortunately I aim for a different scenario: I have to detour a functio... | I acquired my aim with hooking some low-level Windows API functions, not the best solution but it works, Assembler isn't mine...
|
4,317,551 | 4,320,422 | OpenMP: What is the benefit of nesting parallelizations? | From what I understand, #pragma omp parallel and its variations basically execute the following block in a number of concurrent threads, which corresponds to the number of CPUs. When having nested parallelizations - parallel for within parallel for, parallel function within parallel function etc. - what happens on the ... | (1) Nested parallelism in OpenMP:
http://docs.oracle.com/cd/E19205-01/819-5270/aewbc/index.html
You need to turn on nested parallelism by setting OMP_NESTED or omp_set_nested because many implementations turn off this feature by default, even some implementations didn't support nested parallelism fully. If turned on, w... |
4,317,814 | 4,317,834 | No legal conversion to 'this' pointer | Please take a look at this code and run it:
I'm getting very strange error:
Error 1 error C2663: 'Allocator::allocate_help' : 2 overloads have no legal conversion for 'this' pointer
template<class FailureSignal>
class Allocator
{
private:
template<class Exception,class Argument>
void allocate_help(const A... | I noticed Allocate is declared const but allocate_help is not - could that be related to the issue?
|
4,317,863 | 4,317,926 | Tell `string::operator==` to start comparing at the back of the string | Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.
The end of the string is almost unique, and the front is quite comm... | Best I can think of so far is str1.size() == str2.size() && std::equal(str1.rbegin(), str1.rend(), str2.rbegin())
|
4,318,305 | 4,318,352 | Confusion about callback function design | I'm designing a library that will be used to intercept and process incoming messages from a message queue. Library users will write their own message handling functions for different kinds of messages received.
I have a MessageConsumer class that needs to handle messages of different kinds. I combined all handler funct... |
How can these classes be made available to MessageHandler, without making them global?
Users need to derive from your class. What stops them putting all kinds of data members into their derivate, referencing whatever they need?
That's the main advantage of using functors instead of function pointers: It makes void* ... |
4,318,319 | 4,318,462 | What is the correct std::set_union code? | This site claims that set_union is equivalent to the following code:
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_union ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
... | I agree that it looks totally broken. For comparison, here is the STLport code:
template <class _InputIter1, class _InputIter2, class _OutputIter,
class _Compare>
_OutputIter __set_union(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
... |
4,318,375 | 4,319,898 | Qt Application hangs on exit (after QDialog exec) | I'm using Qt to build a UI and I need to have a dialog window show up before the main app window, so that the user can select some files to load ans things like that.
What I've got is a fairly simple main:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
IView *view = new QtView();
view->showV... | I Fixed my problem.
I used the accepted/rejected/finished(int) signal from the QDialog to trigger the show slot on the main app window, and display it if the dialog was accepted.
Thanks for the help anyway.
|
4,318,398 | 4,318,433 | C++ Assigning an int to a char - why does this work without at least a warning? | Why does C++ (and probably C as well) allow me to assign and int to a char without at least giving me a warning?
Is it okay to directly assign the value, like in
int i = 12;
char c = i;
i.e. do an implicit conversion, or shall I use a static_cast<>?
EDIT
Btw, I'm using gcc.
| It was allowed in C before an explicit cast syntax was invented.
Then it remained a common practice, so C++ inherited it in order to not break a huge amount of code.
Actually most compilers issue a warning. If your doesn't, try change its settings.
|
4,318,494 | 4,318,544 | Object Pointer Status After New Constructor Throws Exception - C++ | What is going to be the status of an object pointer when a new class constructor throws an exception in C++? Take the following code for example:
CMyClass * pobjMyClass = (CMyClass *)0xA5A5A5A5;
try
{
pobjMyClass = new CMyClass(); // Exception thrown in constructor
}
catch ( ... ) {}
When this code executes what... | Since the exception is thrown before the assignment takes place, pobjMyClass will be whatever it was before - in your case, 0xa5a5a5a5.
|
4,318,508 | 4,326,805 | C++: function creation using array | Write a function which has:
input: array of pairs (unique id and weight) length of N, K =< N
output: K random unique ids (from input array)
Note: being called many times frequency of appearing of some Id in the output should be greater the more weight it has.
Example: id with weight of 5 should appear in the outpu... | My short answer: in no way.
Just because the problem definition is incorrect. As Axn brilliantly noticed:
There is a little bit of contradiction going on in the requirement. It states that K <= N. But as K approaches N, the frequency requirement will be contradicted by the Uniqueness requirement. Worst case, if K=N, a... |
4,318,643 | 4,318,721 | How to rotate OpenGL to fit iPhone Landscape mode? | I am porting an existing cross-platform program I have made in C++ and with OpenGL/ES on the iPhone. Please keep in mind I do not know anything about Objective-C...
I have just briefly edited the Objective-C files of one of the tutorials to initialize OpenGL properly for the iPhone, and to simply call my C++ multi-plat... | You shouldn't have to do anything to use OpenGL in landscape mode. I suspect you aren't actually going into landscape mode. You need to override shouldAutoRotateToInterfaceOrientation: in your view controller:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
return orientation ==... |
4,318,990 | 4,389,291 | SVG icons not showing up in Qt4 release build in windows | I have a Qt4 application with SVG icons, compiled with mingw (in windows), linked to Qt shared libraries.
When application is run, SVG icons show up in debug and release builds in linux, however in windows SVG icons show up only in debug build but not in release build.
All SVG icons are listed in project.qrc, and proje... | Most likely you will have to include the plugins from your qt dir. This involves making a qt.conf file that is local to your app (see here: http://doc.qt.io/qt-4.8/qt-conf.html , more specifically the [Paths] section), and copy c:\Qt\4.x.x\plugins\imageformats*.dll to your distributable's directory.
|
4,319,044 | 4,320,765 | Segfault when calling a virtual function in another DLL | I have a two-part program where the main core needs to have an adapter registered and then call back into the register. The parts are in separate DLLs, and the core doesn't know the adapter's specifics (besides methods and parameters ahead of time). I've tried setting it up with the following code and recieve a segfaul... | The problem ended up being a stupid mistake on my part.
In another function in the code, I was accidentally feeding a function a Core * instead of the Adapter * and didn't catch it in my read-through. Somehow the compiler didn't catch it either (it should have failed, but no implicit cast warning was given, possibly be... |
4,319,150 | 4,319,874 | Make QListWidget only show 1 item | I have created a class that inherits the QListWidget and is meant to be a stack of cards.
I have overloaded the drag and drop functions to allow a card to be dragged to the table (another object of my program) and now I stumble on another problem.
The QListWidget shows all my items (mainly because I add them to the GUI... | You can use a QStackWiget (the first line of the desription is exactly what you want to ahieve) instead of a QListWidget.
|
4,319,686 | 4,319,761 | Where to get a list of boost libraries included into VS2010 as part of STD? | Where to get a list of boost libraries included into VS2010 as part of STD?
| This should be it: http://msdn.microsoft.com/en-us/library/bb982198.aspx
Strictly speaking these are the TR1 headers that are included with VS2010, I believe some of the types were renamed from their boost counterparts.
<array>
Defines the container template class array and several supporting templates.
<functiona... |
4,319,897 | 4,319,905 | Will this result in a memory leak? | My C++ is pretty rusty so now that I started using it for a hobby project I got to "level up"-again..
#include "stdafx.h"
#include "stdlib.h"
class a
{
public:
void call() { printf("CALL called\n"); }
};
class b
{
public:
b() { this->pointer = new a; }
void call() { this->pointer->call(); }
private:
a... | pointer in b is allocated but never deleted. You'll want to define a destructor for b that deletes a, otherwise you will leak the a pointed to by pointer every time a b goes out of scope:
b::~b()
{
delete pointer;
}
|
4,320,002 | 4,328,105 | Generating Qt Q_OBJECT classes pragmatically | How might one go about making a Q_OBJECT based class (one that has signals and/or slots) through metaprogramming? I don't care if it's templates or preprocessor, neither appears to work and I really need it too.
What I want is to be able to bind arbitrary function like things to Qt signals. Qt signals are incapable o... | Here's what I've discovered about the Qt moc system:
Using some of http://www.codeproject.com/KB/cross-platform/qt_reversing.aspx ...
Since I know that the generated object is going to have one, single slot, and nothing else (that's what it's for) generating the moc stuff with the preprocessor should be possible, thoug... |
4,320,085 | 4,320,196 | Vector of Vector Initialization | I am having a tough time getting my head wrapped around how to initialize a vector of vectors.
typedef vector< vector < vector < vector< float > > > > DataContainer;
I want this to conform to
level_1 (2 elements/vectors)
level_2 (7 elements/vectors)
level_3 (480 elements/vectors)
level_4 (31 element... |
Please do not use nested vectors if the size of your storage is known ahead of time, i.e. there is a specific reason why e.g. the first index must be of size 6, and will never change. Just use a plain array. Better yet, use boost::array. That way, you get all the benefits of having a plain array (save huge amounts of ... |
4,320,087 | 4,320,124 | C++ - calling a method from a class template | I'm currently having a problem with a class template in C++. I'm currently making a hash table.
I'm using a functor as a class template to specify my hash function for each instance of a table.
IE: one table has integers for its keys, strings for its values. Another could have strings for its keys and integers for its ... | operator() in HashString is private and is probably not const-correct. It should be a const member function taking const std::string& as its first parameter. The second parameter does not need to be const.
You seem to be calling it with HashEntry as the second parameter. What is HashEntry? It takes an unsigned int!
Tha... |
4,320,172 | 4,320,366 | C++ std::string Parameter is <Bad Ptr> | I'm using Visual Studio 2010.
I have a class with the following constructor:
CVideoAnnotation::CVideoAnnotation(std::string aPort, DWORD aBaudRate)
I create an instance of CVideoAnnotation as follows:
CVideoAnnotation cVideoAnnotation("COM3", CBR_9600);
'CBR_9600' is a macro that resolves to 9600.
Down in the constru... | If you are implementing CVideoAnnotation in a separate DLL then you are having a well know issue of crossing DLL boundaries when using STL containers. To verify that this is the case create a new constructor taking a const char* instead of std::string and try..
Another thing, instead of std::string prefer to use const ... |
4,320,263 | 4,320,282 | Changing vector value causing seg fault | I am working on a school project for graphs and here I am doing a depth first search down the tree.
void wdigraph::depth_first(int v) const {
static int firstv = -1;
static bool *visited = NULL;
if (firstv == -1) {
firstv = v;
vector<bool> visited(size);
for (int i = 0;... | There are two different variables named visited in your code. Inside the if condition, visited is a vector, but outside this block, on the last line:
visited[v] = true;
visited refers to the bool *visited = NULL defined at the beginning of your code. The segfault occurs because you're trying to dereference a null poin... |
4,320,417 | 4,320,479 | How to get HWND in win32? | Is there way to get the HWND handler of my window?
I'm using win32.
| You could call GetActiveWindow to get the active control in your application, then repeatedly call GetParent on the returned handle until it returns NULL. The last valid handle you get should be the handle of your main window.
The easier way as someone else said is to store the returned value from CreateWindow somewher... |
4,320,610 | 4,320,873 | What is wrong with my syntax in this 1 line bit of code (pointers and references and dereferences oh my)? | The code that I am having trouble with is this line:
result.addElement(&(*(setArray[i]) + *(rhs.setArray[j])));
The + operator in my class is overloaded like this (there are a variety of overloads that can fit in this set, but they all have a similar header):
const Rational Rational::operator+(const Rational &rhs) con... | This code has much more serious issues than you can fix by adding a const or a typecast somewhere.
The result of this code will ultimately be a crash somewhere down the line, because you're passing a pointer to a temporary. Once you finish with line of code that calls addElement, the pointer will be left dangling, and ... |
4,320,618 | 4,322,627 | How to detect const reference to temporary issues at compile or runtime? | I've found recently that most of the errors in my C++ programs are of
a form like the following example:
#include <iostream>
class Z
{
public:
Z(int n) : n(n) {}
int n;
};
class Y
{
public:
Y(const Z& z) : z(z) {}
const Z& z;
};
class X
{
public:
X(const Y& y) : y(y) {}
Y y;
};
class Big
{
public:
Big()
... | I submitted such cases on the clang-dev mailing list a few months ago, but no one had the time to work on it back then (and neither did I, unfortunately).
Argyrios Kyrtzidis is currently working on it though, and here is his last update on the matter (30 Nov 23h04 GMT):
I reverted the previous commit, much
better fi... |
4,320,677 | 4,320,710 | Can't initialize static QList? | I get the following error:
Cube.cpp:10: error: expected initializer before ‘<<’ token
Here's the important parts of the header file:
#ifndef CUBE_H
#define CUBE_H
#include <cstdlib>
#include <QtCore/QtCore>
#include <iostream>
#define YELLOW 0
#define RED 1
#define GREEN 2
#define ORANGE 3
#define BLUE 4
#define WHIT... | You can't initialize an object with <<. The = that is usually there is not operator=() -- it's a special syntax that is essentially the same as calling a constructor.
Something like this might work
QList<int> Cube::colorList = EmptyList() << YELLOW << RED << GREEN << ORANGE << BLUE << WHITE;
where EmptyList() is
QList... |
4,320,776 | 4,322,382 | how to get the name of a button created by QDialogButtonBox? | I'm trying get all the button child widgets of a window. The buttons were created through QDialogButtonBox. How do I get the which one is the cancel/ok/save button?
I have:
QWidget *pWin = QApplication::activeWindow();
QList<QPushButton *> allPButtons = pWin->findChildren<QPushButton *>();
QListIterator<QPushButton*>... | You should use the QDialogButtonBox::button() method, to get the button of the corresponding role.
For instance :
QPushButton* pOkButton = pButtonBox->button(QDialogButtonBox::Ok);
QPushButton* pCancelButton = pButtonBox->button(QDialogButtonBox::Cancel);
// and so on...
Generally speaking, I would say it's a bad idea... |
4,320,940 | 4,323,481 | How to incorporate C++ code in Objective-C project? | I'd like to use some C++ code in an Xcode project but I don't understand either language well enough yet to know how to proceed. I've been at the Obj-C for a while and have an app on the app store, but still learning...
The code I want to use has two files with the same name and .h and .c extensions. I would think th... | First of all, if your files have a .c extension, they are almost certainly C and not C++. All you have to do is add them to the project and target and include the relevant .h file in the Objective-C where you call the C functions.
Now the fact that you used to have a function called main() tells us that you had a stan... |
4,321,375 | 4,321,479 | compiling for other platforms | is it possible to compile (under mac os x using netbeans) C++ code for linux architectures?
| Yes, it's possible. It's called cross-compiling. For instructions how to build and use cross-compiler go here.
|
4,321,577 | 4,321,621 | Windows in Win32 API GUI Programming | I am starting GUI programming and I have a question about windows. I have read some tutorials and they create a window by making a new WNDCLASS, calling RegisterClass and then doing CreateWindow with the name of the new class. I also have seen that to create a Button or something, you use the class name Button when you... | Correct. The main reason you need to define your own WNDCLASS for your windows is to assign your own window procedure that handles messages sent to your window. Standard controls such as buttons and edit controls already have well-defined behaviour as defined by their standard window procedures, hence you can just use ... |
4,321,590 | 4,321,872 | C++ - Undefined reference to `vtable | I was wondering why I was getting this error:
undefined reference to `vtable for BaseRenderer'
I tried searching around but cannot seem to figure this out. I've tried getting rid of the virtual function, removing the constructor, etc.
My BaseRenderer.h
class BaseRenderer : public Renderer
{
Q_OBJECT
public:
... | Since Q_OBJECT is in the parent class, Renderer, you don't have to also include it BaseRenderer. Just get rid of Q_OBJECT and it should work :)
|
4,321,820 | 4,321,845 | closed source library includes boost distribution | I'm using a closed source library (by Activ financial) that includes with their API a boost distribution, both some boost header files and boost library files.
I also use Boost in my existing codebase, and I need to use Activ from my existing code.
Some points
I can encapsulate my use of Activ so that the entire Activ... | Does the library dynamically or statically link to Boost? If statically linked, does the library expose the symbols in the DLL (declspec export)?
If the library is statically linked and the symbols are not exposed, and you do not pass any Boost data structures (smart_ptr, threads, etc) back and forth, you are likely sa... |
4,321,844 | 4,323,072 | C++ with Qt4 plugin development | Lately I have been playing around with the plugin framework provided by the Qt4 Framework, and it works perfectly. There is however one thing that I am unsure of.
In all the examples, the interfaces that were implemented (the actual plugin), had their source code available (the person implementing the interface has acc... | C++ does not allow as much introspection as Java, therefore you cannot just ship "the binaries" and infer the interface from that. In C++ you need the textual description of the interface (the header files).
Someone who wants to develop a plugin for your application needs to have access to
the header file of the plugi... |
4,322,224 | 4,322,262 | Qt slots and inheritance: why is my program trying to connect to the parent instead of the child class? | In a Qt program, I have a QWidget class that is the superclass of another class declared so:
class Renderer : public QGLWidget
{
Q_OBJECT
....
}
class A : public Renderer
{ .... }
Now I have a slot for class A that is not present in Renderer, but when I try to run the program, it fails to make connections to ... | Can you show the code where you connect the signal and slot? Maybe it would also be helpful to see the slot declaration in class A.
EDIT:
Try to add Q_OBJECT macro in subclass A. Another thing could be that the slot is not virtual (but according to what I read that shouldn't make a difference).
These are just guesses,... |
4,322,251 | 4,322,570 | Absolutely deathly wxWidgets Pain | I've never used wxWidgets before, and I'd love to try it out, but I've run into a million problems getting started.
I am using wxWidgets 2.9.1 on Visual Studio 2010. I've gone through the batch build to build every project in every configuration.
I've added the includes and lib references to my project.
When I try to c... | First off, you might reconsider WX. I used it, invested a lot of time and code into products based on it, and it just turned out to be not so hot.
The problem you're having is probably due to not having the unicode flags turned on but only having the unicode version. Apparently anyway. So go into your properties and... |
4,322,337 | 4,325,430 | Sending packet using libpcap speed limitation | I wrote a program that captures Ethernet packets from some NIC (i.e eth0) at high speed (about 1Gbps) and forward traffic using pcap_sendpacket() to another NIC (i.e eth1).
While the forwarder Ethernet interface is not connected to another computer NIC, forwarding speed is desired, but when I connect it, sending speed ... | Because the destination NIC is a 100 Bbps interface :D :p
|
4,322,493 | 4,322,820 | Can't access vector element? | I have this code
vector <int> a[100001];
a[1].push_back(1);
if( a[1][0] == 1)
cout<<"OK!";
But when I try to access a1[0] it says:
CXX0058: Error: overloaded operator not found
Full code:
#include<stdio.h>
#include<vector>
using namespace std;
FILE *f=fopen("chei.in","r");
FILE *g=fopen("chei.out","w");
int t[... | There doesn't seem to be anything wrong with the code. Nearly everyone thought you meant a compile error, but ybungalobill pointed out that retrieving the results of the operator are just not supported by visual studio's debugger.
This isn't anything to worry about if your program does what you expect it to do. Your pr... |
4,322,579 | 4,322,614 | How to pass display output to serial port under Linux? | We have 2 computer. Fist computer's operating system is Linux( any version( not important for me) ) and another operating system is Windows( any version, i don't care). They are connected via 9 pin serial port.
I want to know how can I change Linux's default display output to serial port instead of it's own monitor. I... | It's certainly feasible. The easiest way to do this is just to put a "getty" process on the serial terminal, which is sometimes done by editing /etc/inittab (there will be some examples in there) and then you will see a login prompt via the serial terminal and use all (command-line) programs normally. Historically, Uni... |
4,322,744 | 4,322,869 | C++ Problem with creating thread using Bind | I have a little problem concerning thread and bind interaction.
It is simple, i have this situation
class myclass {
// ...
// ...
void dosome();
void doanother(myclass2, myclass3*);
void run() {
this->_myt = boost::shared_ptr<boost::thread>(
new boost::thread(boost::bind(&myclass::dosome, ... |
You can think of it as an implicit parameter. Or you can think of this like bind needs to call your member function like something->your_member(), so you must tell it what something is.
You don't store the shared_ptr anywhere, in the second example, so it will be destroyed immediately after it's created. The thread ob... |
4,322,794 | 4,322,825 | How to save data in C/C++? | In the internet there are databases(mysql, oracle etc.) where I can send the informations submitted by the HTML input fields with PHP or any other server side language.
How is this working in C/C++? How can I let a user input something and them save the inputted value?
| You can either:
Make use of the standard file handling functions/classes.
Embed a tiny database.
Talk to a database server using a standard interface.
BTW, these are common for all languages.
|
4,322,840 | 8,139,620 | Is it possible to detect GDI leaks from the Visual Studio debugger? | Leaking GDI objects can be seen from the task manager or from Process Explorer. (Well you don't see the leaks, but you can see if object uasage count continually goes up.)
There are also tools that allow to view GDI objects by type, such as GDIView[a], DeLeaker, DPUS or the GDIDebug (sourecode).
[a] Note that I conside... | GDI objects do not have to be checked individually (notreally), they can be in charge with Deleaker - and you'll know where the leak. Read the instructions carefully and view a demo video :http://deleaker.com/
|
4,322,909 | 4,322,971 | Doing multiple tasks at once? (combining a GUI related function to carryout some process) | I'm sorry if the title sounds "off", but to elaborate further, this is my problem - Basically I've written a simple Winsock server which passes information (text messages) between connected clients (This is the console application). Now for this program I've tried combining what I've learned from the win32api with the ... | A GUI works through an event-driven message-loop. That message-loop dispatches incoming events to function-calls. So if you press a button, a function is called, which then can call for instance the network send-function. If you need to send (or receive) large amounts of data, you should create a separate thread and me... |
4,323,008 | 4,323,060 | Why is initialization of integer member variable (which is not const static) not allowed in C++? | My C++ compiler complains when i try to initialize a int member variable in class definition. It tells "only static const integral data members can be initialized within a class". Can you please explain the rationale behind this restriction (if possible with example).
| The rationale is the "low-level" nature of C++. If it would allow this, the compiler would need to generate initialization code for all constructors which is not entirely clear to the developer.
After all it might be necessary to initialize members of base classes on the construction of a derived class even when the b... |
4,323,023 | 4,324,594 | How will be a reference treated in these cases? | I know when a reference is parameter of a function and that function is inlined, then it would be possible for the reference to be the referent itself and not necessarily a pointer to it, but what about when a reference is not a parameter but is local to a function or global, or is output of a function which is inlined... | David Rodríguez - dribeas already pointed out in a comment that the standard gives compilers quite a bit of latitude, when it comes to references. They may or may not take space; they're not proper objects themselves, etc.
The behavior you describe for function arguments of reference type (eliminated during inlining) i... |
4,323,046 | 4,323,062 | Timestamp of file in c++ | i want to check a file to see if its been changed and if it is, then load it again.. for this, i started with the following code which is getting me nowhere...
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
struct stat st;
int ierr = sta... | That's because you're calling stat() outside the loop.
The result from stat() is correct at that particular moment. you need to call stat() again each time you want to check it.
|
4,323,111 | 4,323,617 | Opening database in invalid location causes memory leak | I am using qt 4.5.3 to access the sqlite database, like this :
class db : private boost::noncopyable
{
public:
db( QString file ) : filename( file ),
realdb( NULL ),
theConnectionEstablished( false )
{
}
~db()
{
if ( NULL != realdb.get() )
{
realdb.... | Had a browse through the Qt and sqlite sources ... interesting.
Reading the manual for sqlite3_open16(), http://www.sqlite.org/c3ref/open.html, one finds the following quote:
Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to s... |
4,323,471 | 4,323,758 | Newbie question f2c compilation problem: cc1plus error: /include: not a directory What does this mean? | I am having problems with compiling code on my Mac (OS X, 10.6.5).
The code uses f2c.
I don't understand the error, and would really appreciate any help. I wondered if it might be a problem with my compiler, and just in case I reinstalled Xcode, which installs a new g++ compiler. But I still get the same error.
Here'... | This may be an error in the installation of your gcc compiler. It seems it may be looking for includes in /usr/include, but it is missing the first part of the directory. Try executing:
$ gcc -v
to see what directories the gcc you're using has by default. In my case, I see
--prefix=/usr
as one of the options.
|
4,323,616 | 4,324,226 | List the drawback (performance/maintenance etc.,) in having all setter functions as SLOTS in Qt? | Is there any drawback (performance/maintenance etc.,) in having all setter functions as SLOTS in Qt?
Some of the disadvantages i see are,
1) Unnecessary call of MOC and Unnecessary moc files created during compile time
2) Break in the exception handling chain, since exceptions are not passed in signal-slot connection
3... | If you call the setters directly, you can avoid most of the drawbacks you mention. It will behave as any other normal call. The only drawback in that case would be the longer compiler time and bigger bin size.
If you call all your setters by emitting signals, then:
1) More complex code; since you have to remember t... |
4,323,697 | 4,325,604 | Is it possible to delete a file that is opened by a process under windows? | For testing and simulation purposes I would like to delete a file that is currently open by my process.
The CreateFile docs state that it is possible to open a file in a mode (FILE_SHARE_DELETE) that allows the file the open handle is pointing to to be deleted by another operation. (And I already tried and confirmed th... | There is no way to do this.
The closest way to do something like this is to schedule delete on reboot using MoveFileEx with a target filename of NULL, and MOVEFILE_DELAY_UNTIL_REBOOT in the dwFlags parameter.
|
4,323,799 | 4,324,796 | How to allocate from heap with the correct memory alignment for InterlockedIncrement function? | This code seems to work, but have I used the InterlockedIncrement function correctly? The correct memory alignment of m_count is of my primary concern. Assume we're on a x86-64 system and compile a 64-bit application (in case that matters). By the way, for my actual purposes I can't declare m_count as a volatile long a... | The heap allocator already aligns returned addresses to the native platform word size. 4 bytes for x86, 8 bytes for x64. You are using long, 32-bit on either platform for MSVC. No need to jump through the _aligned_malloc() hoop.
|
4,323,802 | 4,323,814 | C++: is it right to delete all declarations in public and private? | I am learning C++ and I am not clear about the destructor of a class. For example:
class A:
{
public:
int valueA;
private:
int valueB;
};
A:~A()
{
delete valueA;
delete valueB;
}
So, basically is it right to delete every declarations in the public and private?
| No, you only need to delete that which has been allocated using new. Simple value types like ints never need to be deleted.
If your class did include data dynamically allocated using new either by the constructor or later by some other method then the destructor should typically de-allocate all of it, regardless of wet... |
4,324,102 | 4,324,211 | Can I return early from a variable-argument function? | Suppose I have two C++ functions for debug output:
void Trace( const wchar_t* format, ... )
{
va_list args;
va_start( args, format );
VarArgTrace( format, args );
va_end( args );
}
void VarArgTrace( const wchar_t* format, va_list args )
{
WCHAR buffer[1024];
//use ::_vsnwprintf_s to format the ... | The only requirement on an early return is that if you have used (executed) va_start(), you must use va_end() before you return.
If you flout this rule, you'll get away with it on most systems, but some system somewhere needs the va_end(), so don't risk omitting it. It is undefined behaviour to omit it.
Other than tha... |
4,324,121 | 4,324,196 | Tutorials / books on understanding assembly output | There are times when understanding disassemblies from higher languages such as C or C++ are useful. Reading a book on assembly is obviously a necessary part of understanding compiler output, but in my experience writing assembly code from scratch is quite a different thing than reading and understanding the opcodes a c... | Many similar questions here on SO:
Learning Assembly
Resources for learning ARM assembly
Good x86 assembly book
Most posters aim to the same thing as you, that is read assembly code and not write new one.
|
4,324,143 | 4,324,540 | How to read from file UTF simbols as if they were UTF code? | So I have a file - html file there are lots of simbols like &'""""</\>9()!@#+=- I need to convert them into a form that can be copied from output screen so to be after passed to std::string str ("Here should be UTF simbols"); how to do such thing (using C++ boost)
| This code assumes the compiling system uses a superset of ASCII, which is reasonable on today's systems. It gives a string literal as a std::string, including surrounding quotes. The input data is treated as generic bytes rather than required to be UTF-8.
std::string string_literal(int length, char const *data) {
s... |
4,324,385 | 4,324,473 | Does this code work universaly, or is it just my system? | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
locale system("");
locale::global(system);
wcin.imbue(system);
wstring data;
getline(wcin,data);
wcout.imbue(system);
wcout << data << L" length=" << data.length() << en... | It's your system. Locale names are not part of the C++ standard, so "en_US.UTF-8" is not universally valid. It's not even certain that a locale similar to it exists.
|
4,324,426 | 4,324,537 | Calling c function in a lib file from c++ | I have to call a c function declared in a lib file from c++. What instructions/attributes/configuration I have to set for this?
| Do you have a header file for the library? If so it should have
extern "C" {
blah blah
}
stuff in it to allow it to be used by C programs. If not, then you can put that around the include statement for the header in your own code. E.g.
extern "C" {
#include "imported_c_library.h"
}
|
4,324,441 | 4,324,667 | Testing stream.good() or !stream.eof() reads last line twice |
Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?
I have the following piece of code:
ifstream f("x.txt");
string line;
while (f.good()) {
getline(f, line);
// Use line here.
}
But this reads the last line twice. Why does this happen and how do I fix it?
Something very similar ... | You very, very rarely want to check bad, eof, and good. In particular for eof (as !stream.eof() is a common mistake), the stream currently being at EOF does not necessarily mean the last input operation failed; conversely, not being at EOF does not mean the last input was successful.
All of the stream state functions ... |
4,324,542 | 4,336,010 | What is the Windows equivalent for en_US.UTF-8 locale? | If I want to make the following work on Windows, what is the correct locale and how do I detect that it is actually present:
Does this code work universaly, or is it just my system?
| Basically, you are out of luck: http://www.siao2.com/2007/01/03/1392379.aspx
|
4,324,703 | 4,324,745 | Should an octree be rebuilt every frame? | When using an octree for collision detection in a game, should the tree be rebuilt every frame or is there a better way assuming half the objects move in a frame?
| If the scene changes with every frame, then you have to redo the tree.
|
4,324,735 | 4,325,286 | Efficient exit from multithreaded application (specifics) | I've read a few sources on proper methods of bubbling a message out from a thread to all other threads to exit gracefully (every thread performs it's own exit routine). Of these, I liked the idea of a global atomic boolean that can be flagged from any thread, and all other threads check this flag to perform an exit rou... | In Windows, I use QueueUserAPC to call a function which throws an exception, causing threads to exit cleanly.
I wrote more about the details in this answer here:
How do I guarantee fast shutdown of my win32 app?
In summary, here's what happens:
Say thread A wants to terminate thread B (and then C, D, ...)
Thread A cal... |
4,324,763 | 4,324,780 | Can we have functions inside functions in C++? | I mean something like:
int main()
{
void a()
{
// code
}
a();
return 0;
}
| Modern C++ - Yes with lambdas!
In current versions of c++ (C++11, C++14, and C++17), you can have functions inside functions in the form of a lambda:
int main() {
// This declares a lambda, which can be called just like a function
auto print_message = [](std::string message)
{
std::cout << message... |
4,324,870 | 4,325,105 | Is this code thread-safe? | Let's say we have a thread-safe compare-and-swap function like
long CAS(long * Dest ,long Val ,long Cmp)
which compares Dest and Cmp, copies Val to Dest if comparison is succesful and returns the original value of Dest atomically.
So I would like to ask you if the code below is thread-safe.
while(true)
{
long dummy... | Edit. An edit to the question means most of this isn't relevant. Still, I'll leave this as all the concerns in the C# case also carry to the C++ case, but the C++ case brings many more concerns as stated, so it's not entirely irrelevant.
Yes, but...
Assuming you mean that this CAS is atomic (which is the case with C# ... |
4,325,144 | 4,325,624 | When do programmers use Empty Base Optimization (EBO) | I was reading about Empty Base Optimization(EBO). While reading, the following questions popped up in my mind:
What is the point of using Empty class as base class when it contributes nothing to the derived classes (neither functionality-wise, nor data-wise)?
In this article, I read this:
//S is empty
class struct... | EBO is important in the context of policy based design, where you generally inherit privately from multiple policy classes. If we take the example of a thread safety policy, one could imagine the pseudo-code :
class MTSafePolicy
{
public:
void lock() { mutex_.lock(); }
void unlock() { mutex_.unlock(); }
private:
... |
4,325,154 | 4,325,223 | Delete objects of incomplete type | This one made me think:
class X;
void foo(X* p)
{
delete p;
}
How can we possibly delete p if we do not even know whether X has visible destructor? g++ 4.5.1 gives three warnings:
warning: possible problem detected in invocation of delete operator:
warning: 'p' has incomplete type
warning: forward declaration of... | From the standard [expr.delete]:
If the object being deleted has
incomplete class type at the point of
deletion and the complete class has a
non-trivial destructor or a
deallocation function, the behavior is
undefined.
So, it's UB if there's nontrivial stuff to do, and it's ok if there isn't. Warnings aren'... |
4,325,244 | 4,325,304 | trying to compile stir library: error: invalid conversion from ‘const char*’ to ‘char*’ | First, I'm pretty new to C++ and C so be easy on me :-)
Second, I know this question has be asked many times in many forms before, but I could figure
how to bend the answers to my case ...
I am trying to compile a file called utilities.cxx from the STIL library which has some kind of and "open source" license (not rea... | This line is causing the error:
char * location_of_dot =
strchr(find_filename(file_in_directory_name),'.');
strchr() returns a const char*, not a char* when called with a const char* as the first argument (I'm assuming find_filename() returns a const char *, otherwise you wouldn't be seeing this error).
Since you... |
4,325,295 | 4,375,315 | Multi Pointer X (MPX) support | I'm wondering how multiple pointers should/could be handled by a high level application.
I'm mostly interested about how MPX (Multi Pointer X - for Xorg) works. What GUI libraries support it?
It seems like latest versions of Qt and GTK should support it, but cannot find any demo, tutorial or documentation.
| Experimental support for MPX in GTK+ can be found here. Since that's a work in progress, documentation is very scarce but still might get you started.
There's documentation about MPX itself here.
Note that existing applications using only one pointer will be able to run unchanged on an MPX-aware server. If you want you... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.