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
1,568,807
1,568,830
How to define (non-method) functions in header libraries
When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings? When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains ...
If you really want to define the function (as opposed to declaring it), you'll need to use inline to prevent linker errors. Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.
1,568,949
1,568,964
Why isn't the gcc 4.x.x series compilers installed by MinGW by default?
Currently, MinGW's only installs the 3.x.x series of the gcc compiler by default. However, it looks like the 4.x.x series of compilers have been out for some time, and as others have mentioned, it seems to work just fine. Is there any reason why it hasn't moved to the 4.x.x versions yet, and any reason why I shouldn'...
GCC4's C++ ABI has changed from GCC3, and it includes a lot of new features (like its tree vectorization) that a lot of people still consider "experimental." There are still a few Linux distributions still using GCC3 for that reason.
1,569,085
1,569,103
Prevent Duplicate Entry into HashTable C++
I was wondering if i could get some help to prevent a duplicate entry into my hashtable: bool hashmap::put(const stock& s, int& usedIndex, int& hashIndex, int& symbolHash) { hashIndex = this->hashStr( s.m_symbol ); // Get remainder, Insert at that index. symbolHash = (int&)s.m_symbol; usedIndex = hashIndex;...
Just look at the objects you're storing in that index. If you have to move the index because of a collision check those also. If they match what you're trying to store, throw an exception or something. I'm guessing at your code so... bool hashmap::put(const stock& s, int& usedIndex, int& hashIndex, int& symbolHash) { ...
1,569,254
1,569,268
LNK2019 and LNK1120 with templated function
After having some problems with these two linker errors on SO, I have them again. However, this time the source seems to lie at another point. compiler error shows that it cannot find a function with signature ""public: unsigned int __thiscall MyClass::myFunction<unsigned int>(int)const ". However, moving the contents ...
Because in main.cpp, the compiler can find the definition of the template function. Templates cannot be compiled, the compiler needs to be able to see the definition of the file, and it's can't see across files. Either include myClass.cpp in myClass.h, or just define everything in the header.
1,569,261
1,569,327
What is the difference, usage-wise, between defines/macros/structs and consts/funcs/classes? (C++)
I know that the difference between defines and constants is that constants have type, and that between macros and functions, functions are called, and typed, whereas macros are untyped inline. Not so much the difference between structs and classes, but I don't think there is one, besides the public/private default thi...
Typically, in a C++ program I might use a struct for a simple aggregation of data, such as a Point structure that contains an x and a y. I would use a class for objects that have behaviour (member functions) associated with them. This is just a convention of course, since the compiler treats them almost identically exc...
1,569,554
1,569,560
Is putting a function within an if statement efficient? (C++)
I've seen statements like this if(SomeBoolReturningFunc()) { //do some stuff //do some more stuff } and am wondering if putting a function in an if statement is efficient, or if there are cases when it would be better to leave them separate, like this bool AwesomeResult = SomeBoolReturningFunc(); if(AwesomeRes...
I'm not sure what makes you think that assigning the result of the expression to a variable first would be more efficient than evaluating the expression itself, but it's never going to matter, so choose the option that enhances the readability of your code. If you really want to know, look at the output of your compil...
1,569,726
1,569,760
Difference: std::runtime_error vs std::exception()
What is the difference between std::runtime_error and std::exception? What is the appropriate use for each? Why are they different in the first place?
std::exception is the class whose only purpose is to serve as the base class in the exception hierarchy. It has no other uses. In other words, conceptually it is an abstract class (even though it is not defined as abstract class in C++ meaning of the term). std::runtime_error is a more specialized class, descending fro...
1,569,778
1,569,788
C++ interview preparation
I have a Phone interview coming up next with with a company which works in financial software industry. The interview is mainly going to be in C++ and problem solving and logic. Please tell me the method of preparation for this interview. I have started skimming through Thinking in C++ and brushing up the concepts. Is ...
Make sure you know your basic data structures and algorithms. You're more likely to be asked about that stuff than something higher up the food chain. Those are usually saved for the in-person interview. Put another way: be solid with the fundamentals and solid with your C++ syntax. Also, knowledge of common libraries ...
1,569,829
1,570,220
Open Source C++ game engine math libraries?
I'm looking for a free to use game engine math library. Specifically I'd like a good matrix and vector implementation. And everything needed to move objects in 3D space. Does anyone know any good ones? I'm targeting OpenGL. I'd like to write them myself but don't have the time.
I'd recommend OpenGL Mathematics (GLM) Though if you want physics with your math you could go with Bullet Physics Library Finally if you want an entire engine i'd go with OGRE
1,569,939
1,571,089
Rendering different triangle types and triangle fans using vertex buffer objects? (OpenGL)
About half of my meshes are using triangles, another half using triangle fans. I'd like to offload these into a vertex buffer object but I'm not quite sure how to do this. The triangle fans all have a different number of vertices... for example, one might have 5 and another 7. VBO's are fairly straight forward using...
VBOs and index buffers are an orthogonal things. If you're not using index buffers yet, maybe it is wiser to move one step at a time. So... regarding your question. If you put all your triangle fans in a vbo, the only thing you need to draw them is to setup your vbo and pass the index in it for your fan start glBind...
1,569,962
1,588,904
Any good C++/C NNTP libs?
I came across some crusty and limited efforts awhile back but I was wondering if there was something truly functional that I missed, preferably in C++ but C is better than nothing.
W3Cs libwww exposes a complete, standards compliant NNTP implementation. It is cross platform and (partially) well documented. User guide The API-of-interest: WWWNews client API I hope this is helpful.
1,570,330
1,570,616
Why does memcpy fail copying to a local array member of a simple object?
Classic memcpy gotcha with C arrays as function arguments. As pointed out below, I have an error in my code but the erroneous code worked in a local context! I just encountered this weird behaviour in a porting job, where I'm emulating the Macintosh Picture opcode playback using objects. My DrawString object was drawin...
This is probably a good example of why (in my opinion) it's a bad idea to typedef array types. Unlike in other contexts, in function declarations a parameter of array type is always adjusted to an equivalent pointer type. When an array is passed to the function it always decays into a pointer to the first element. Thes...
1,570,364
1,570,743
How to capture ping's return value in C++
Does anyone know, how to capture ping's return value in c++? According to this link: ping should return 0 on success, 1 on failure such as unknown host, illegal packet size, etc. and 2 On a unreachable host or network. In C++ I called ping with the system (), e.g. int ret = system("ping 192.168.1.5");. My problem is, ...
If you are on Windows, it might be better to use IcmpSendEcho2 directly to implement the ping functionality in your application.
1,570,377
1,570,396
C++ linked list memory management
I'm attempting to craft my own basic singly linked list in C++ as a learning exercise, and I'm encountering some difficulty in the memory management department. As it stands I have... A 'Node' class: class Node { public: char *value; Node *next; Node(); ~Node(); }; Node::Node() { } Node::~Node() { ...
The data pointed to by the various Node::value aren't dynamically allocated, so you shouldn't delete them. Applying the concept of "ownership", nodes should either make their own copies of data, which they own and can delete, or nodes don't own data, so they shouldn't be responsible for deleting it. You can also implem...
1,570,382
1,574,863
Why is my DLL failing to register?
I am building a project in VS2005 and several of my DLLs are failing to register. The error message I am getting in Visual Studio is: Project : error PRJ0019: A tool returned an error code from "Registering ActiveX Control..." which is nicely vague. When I register the DLL manually through the command line (using r...
Microsoft had recently released a Security Update for ATL (KB971090). It is un update on top of MSVS2005sp1 and it's both compilate-time and runtime compatibility breaker. Check if your building environment has this patch. References: ATL Security Update: http://msdn.microsoft.com/en-us/visualc/ee309358.aspx Breaking...
1,570,471
1,570,560
C++ inheritence for on-stack objects
I have a base class, Token. It has no implementation and as such acts as a marker interface. This is the type that will be used by callers. { Token t = startJob(jobId); // ... (tasks) // t falls out of scope, destructors are called } I have a derived class, LockToken. It wraps around a mutex and insures th...
You are returning a Token by value. That means that you are not returning a LockToken, but rather a Token copy constructed from your LockToken instance. A much better approach would be to use boost::shared_ptr. That way your clients can copy things around without needing to worry about deletion. Something like this:...
1,570,516
1,570,596
Warning linking boost lib in WDK build ("LNK4217: locally defined symbol _ imported in function _")
I'm building the below example boost-consuming user-mode app with the WDK, but I'm getting the following errors when linking with the boost libraries that I built earlier using bootstrap and .\bjam, from the same terminal window. IIUC, MSDN says it's because the (hideously mangled) function - which appears to be a C++ ...
You are explicitly including ..\boost_1_40_0\stage\lib\libboost_program_options-vc100-mt.lib in the link. You should let the boost auto_link stuff configure do the correct #pragma comment(lib, ...) stuff ensure you bring in the right library and set the linker search path correctly. The most likely thing is that the b...
1,570,737
1,570,797
Why Access Violation for cout and Stack Overflow for printf
I wanted to know why Access Violation occurs for cout and Stack Overflow for printf in the following two code snippets. I wanted to know why Access Violation for the first code instead of the Stack Overflow. First code which I get Access Violation : void Test(); void Test() { static int i = 0; cout << i++ ...
I assume you understand that both functions crash due to exhaustion of the stack after an attempt at infinite recursion. I think what you are asking is: why would the cout example not crash with "Stack Overflow" also? I do not think the answer has to do with the compiler's detection of tail recursion. If the compiler...
1,570,917
1,570,963
Extracting C / C++ function prototypes
I want to do this: extract_prototypes file1.c file2.cpp file3.c and have whatever script/program print a nice list of function prototypes for all functions defined in the given C / C++ files. It must handle multi-line declarations nicely. Is there a program that can do this job? The simpler the better. EDIT: after try...
The tool cproto does what you want and allows to tune the output to your requirements. Note: This tool also only works for C files.
1,570,922
1,572,121
Winsock2: How to allow ONLY one client connection at a time by using listen's backlog in VC++
I want to allow only one connection at a time from my TCP server. Can you please tell, how to use listen without backlog length of zero. I m using the code(given below), but when i launch 2 client one by one, both gets connected. I m using VC++ with winsock2. listen(m_socket,-1); passing zero as backlog is also not wo...
If you can indeed limit your application to only use Winsock 2, you can use its conditional accept mechanism: SOCKET sd = socket(...); listen(sd, ...); DWORD nTrue = 1; setsockopt(sd, SOL_SOCKET, SO_CONDITIONAL_ACCEPT, (char*)&nTrue, sizeof(nTrue)); This changes the stack's behavior to not automatically send SYN-ACK r...
1,571,033
1,571,080
Are large include files like iostream efficient? (C++)
Iostream, when all of the files it includes, the files that those include, and so on and so forth, adds up to about 3000 lines. Consider the hello world program, which needs no more functionality than to print something to the screen: #include <iostream> //+3000 lines right there. int main() { std::cout << "Hello, ...
If you worry about the size of <iostream> when all you want is print a line of text, try <cstdio> and std::puts(). (Seriously, why do people use printf() or cout when the much simpler and quicker puts() fits the bill perfectly? It even appends an appropriate line feed automatically...) In a serious application, the siz...
1,571,115
1,571,129
C++ Abstract class construction and destruction
class base { base () { } virtual ~base () { } } class middleBase { middleBase () { } middleBase (int param) { } ~middleBase () { } } class concrete : public middleBase { concrete () { } concrete (int param) { // process } ~concrete () { // delete something } } Error is : undefinded re...
class base { public: // constructor should be accessible by derived class base () { } virtual ~base () { } }; // add semicolon class middleBase : public base // you missed the declaration { public: middleBase () { } middleBase (int param) { } virtual ~middleBase () { } }; class concrete : pub...
1,571,215
1,571,246
C++: iterating over a list of a generic type
Yet again I find myself struggling with the C++ syntax. I'm trying to iterate over a list of generic objects. That is I have objects of a class Event<Q>, crammed into a std::list<Event<Q> >. So I'm trying to get an iterator over the list and intuitively thought that std::list<Event<Q> >::iterator it; for (it = events.b...
Sure this should work, but it sounds like you either have one or both of the following in action. Have Q a template parameter or a type that somehow otherwise depend on it (typedef to it). Put a typename before std::list then, so that the compiler knows that ::iterator is a type and can proceed analysis properly (it ...
1,571,340
1,571,360
What is the "assert" function?
I've been studying OpenCV tutorials and came across the assert function; what does it do?
assert will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs. For example: assert(length >= 0); // die if length is negative. You can also add...
1,571,731
1,571,846
Is it possible to change the temporary object and to pass it as an argument?
Is it possible to change the temporary object and to pass it as an argument? struct Foo { Foo& ref() { return *this; } Foo& operator--() { /*do something*/; return *this; } // another members }; Foo getfoo() { return Foo(); } // return Foo() for example or something else void func_val(Foo x) {} void func_r...
func_val(--getfoo()); // #1 OK? Yes, OK. The operator-- is a member-function, which is called, and which returns itself (and lvalue referring to itself). The object is then copied into the parameter of func_val. Notice that return value optimization is not allowed to apply, since the temporary created by getfoo() ...
1,572,016
1,572,030
What's the ampersand for when used after class name like ostream& operator <<(...)?
I know about all about pointers and the ampersand means "address of" but what's it mean in this situation? Also, when overloading operators, why is it common declare the parameters with const?
In that case you are returning a reference to an ostream object. Strictly thinking of ampersand as "address of" will not always work for you. Here's some info from C++ FAQ Lite on references. As far as const goes, const correctness is very important in C++ type safety and something you'll want to do as much as you can....
1,572,170
1,572,470
Use CArray class from MFC in C++ Builder application
There is a need to pass CArray instance to an external DLL from my application written in C++ Builder. Is there a way to utilize MFC from C++ Builder? If yes, how? Addendum: this DLL is not mine and I cannot change it.
C++ Builder doesn't support MFC because the Microsoft and Borland C++ runtimes are incompatible. See http://www.parashift.com/c++-faq-lite/compiler-dependencies.html#faq-38.9
1,572,290
1,572,469
Fastest way to scan for bit pattern in a stream of bits
I need to scan for a 16 bit word in a bit stream. It is not guaranteed to be aligned on byte or word boundaries. What is the fastest way of achieving this? There are various brute force methods; using tables and/or shifts but are there any "bit twiddling shortcuts" that can cut down the number of calculations by givi...
Using simple brute force is sometimes good. I think precalc all shifted values of the word and put them in 16 ints so you got an array like this (assuming int is twice as wide as short) unsigned short pattern = 1234; unsigned int preShifts[16]; unsigned int masks[16]; int i; for(i=0; i<16; i++) { preShifts[...
1,572,365
1,572,543
what is the most unobtrusive way of using precompiled headers in Visual C++?
Say I have a single project, with files A.cpp, B.cpp, C.ppp and matching header files (and that's it). The C++ files include system headers or headers from other modules. I want to compile them to a library with command line actions (e.g., using Make), using 'cl', with the precompiled headers feature. What are the step...
Precompiled Headers are done by creating a .cpp that includes the headers you want to be pre-compiled. Normally, stdafx.cpp is used for this purpose. Create a .cpp that includes the headers you want to be precompiled -- normally this file would be called stdafx.cpp Add the .cpp to your project Compile that file with /...
1,572,420
1,572,460
Creating a new primitive type
Is there a way to create a new type that is like one of the basic types (eg char), and can be implcitly converted between, but will resolve diffrently in templates, such that for example, the following code works? typedef char utf8; template<typename T>void f(T c); template<> void f<char>(char c) { std::cout << "as...
I heard a rumour that C++0x will bring strong typedefs which will allow for the utf8 class in your case to be distinguishable from the char, but that doesn't exist currently. Maybe Boost's strong typedef would help, but I don't know.
1,572,427
2,184,204
Problem with Berkeley DB and C++
I'm trying to write a simple C++ program that uses Berkeley DB for storage. The key of the database is of type time_t and the data is an integer. I need to take the difference between two adjacent data in a between two key. I open a cursor with the flag DB_SET_RANGE and then i use DB_NEXT to iterate. My problem is that...
Some of the reasons why you may want to provide a custom sorting function are: You are using a little-endian system (such as x86) and you are using integers as your database's keys. Berkeley DB stores keys as byte strings and little-endian integers do not sort well when viewed as byte strings. There are several soluti...
1,572,586
1,572,918
C++: how to deal with const object that needs to be modified?
I have a place in the code that used to say const myType & myVar = someMethod(); The problem is that: someMethod() returns const myType I need to be able to change myVar later on, by assigning a default value if the object is in an invalid state. So I need to make myVar to be non-const. I assume I need to make myV...
I wouldn't use the const_cast solutions, and copying the object might not work. Instead, why not conditionally assign to another const reference? If myVar is valid, assign that. If not, assign the default. Then the code below can use this new const reference. One way to do this is to use the conditional expression...
1,572,705
1,572,921
How to convert long to LPCWSTR?
how can I convert long to LPCWSTR in C++? I need function similar to this one: LPCWSTR ToString(long num) { wchar_t snum; swprintf_s( &snum, 8, L"%l", num); std::wstring wnum = snum; return wnum.c_str(); }
Your function is named "to string", and it's indeed easier (and more universal) to convert to a string than to convert "to LPCWSTR": template< typename OStreamable > std::wstring to_string(const OStreamable& obj) { std::wostringstream woss; woss << obj; if(!woss) throw "dammit!"; return woss.str(); } If you h...
1,572,751
1,572,819
How do I find out where an object was instanciated using gdb?
I'm debugging an application and it segfaults at a position where it is almost impossible to determine which of the many instances causes the segfault. I figured that if I'm able to resolve the position at which the object is created, I will know which instance is causing the problem and resolve the bug. To be able to ...
Have you tried using a memory debugging library (e.g. dmalloc). Many of these already instrument new, etc. and records where an allocation is made. Some are easier to access from gdb than others though. This product has a memory debugging feature that does what you want: http://www.allinea.com/index.php?page=48
1,572,909
1,572,946
Is reinterpreting a member function pointer a 'good idea'?
I have a worker thread, which holds a list of 'Thread Actions', and works through them as an when. template <class T> class ThreadAction { public: typedef void (T::*action)(); ThreadAction(T* t, action f) : func(f),obj(t) {} void operator()() { (obj->*func)(); } void (T::*func)(); T* obj; }; It's nor...
This is definitely not supported behavior, and can potentially cause your program to crash. Basically, you need to make a wrapper for TheirClass::enable() that will have the proper return type. A simple one-liner will suffice: public: void enableWrapper() { enable(); }; Then call: myActionThread->addAction( ne...
1,573,168
1,573,190
Error: expected constructor, destructor, or type conversion before ';' token?
I'm trying to compile my code to test a function to read and print a data file, but I get a compiling error that I don't understand - "error: expected constructor, destructor, or type conversion before ';' token". Wall of relevant code-text is below. struct Day { int DayNum; int TempMax; int TempMin; double Pr...
The line with the error looks like you're trying to call GetMonth -- but at the global level, a C++ program consists of a series of declarations. Since a function call isn't a declaration, it can't exist in isolation at the global level. You can have a declaration that's also a definition, in which case it can invoke a...
1,573,203
1,573,258
C++ matrix transposion. Boost uBLAS and double*?
I need to do a in-place transposition of a large matrix(so the simplest way to allocate another matrix and transpose to it won't work). Unfortunately, this large matrix isn't square. And worse, the matrix is stored in an array of doubles with number of columns and rows stored separately. I found that boost has the uBLA...
If you have very big matrices and you dont want to store the temporary copies one solution would be to wrap your matrix array into the class and provide different adapters which will iterate through the elements in normal or transposed way. This is not very cache efficient but saves memory on large matrices.
1,573,225
1,573,271
Why do I have __stdcall?
I am starting doing some directX programming. I am using this tutorial that I have found from the Internet. I am just wondering why the CALLBACK has been defined as _stdcall and why WINAPI is as well. I thought __stdcall was used when exporting functions that will be compiled as a dll. However, as WindowProc and WINAPI...
__stdcall refers to the calling convention, and doesn't necessarily have to do with exporting functions. Take a look at Wikipedia's article on calling conventions if you want to know more. In brief, the compiler needs to know where to pass the parameters to your function, on the stack or in registers etc.
1,573,732
1,573,773
Using dlopen, how can I cope with changes to the library file I have loaded?
I have a program written in C++ which uses dlopen to load a dynamic library (Linux, i386, .so). When the library file is subsequently modified, my program tends to crash. This is understandable, since presumably the file is simply mapped into memory. My question is: other than simply creating myself a copy of the fil...
If you rm the library prior to installing the new one, I think your system will keep the inode allocated, the file open, and your program running. (And when your program finally exits, then the mostly-hidden-but-still-there file resources are released.) Update: Ok, post-clarification. The dynamic linker actually comple...
1,573,806
1,573,868
When are member data constructors called?
I have a global member data object, defined in a header (for class MyMainObj) like this. class MyMainObj { MyDataObj obj; } MyDataObj has a default constructor. When is the constructor for MyDataObj called? Is it called as part of the creation of MyMainObj?
MyDataObj in this case is not a member of MyMainObj, it's a local variable. But, constructors for data members are called in your class's constructor. The default constructor for every member is called before execution reaches the first line in the constructor, unless you explicitly specify a constructor using an initi...
1,574,121
1,574,199
Precompiled headers with DLL solutions. Cannot open precompiled header file
This worked without error when this solution worked off of .lib files instead of .dll files. I have all of my projects except one currently using a precompiled header, without error. The precompiled header is called "LudoGlobal.h". I am trying to link the last project to this precompiled header (which exists in a s...
Are you using "automatically generate", or "use precompiled header" on the project and "create precompiled header" on the one cpp file? The latter is more efficient, but I've seen the per-file configuration on projects get accidentally reset, so that the "stdafx.cpp" (or whatever) file no longer generates the precompi...
1,574,286
1,574,299
Vector assignment problem
#include "iostream" #include "vector" using namespace std; const vector<int>& Getv() { vector<int> w(10); w[0]=10; cout<<w.size()<<endl; return w; } //Now when I write in main: vector<int>v = Getv();//Throws exception //and the below rows has no effect vector<int>v; v=Getv()//w does not change please what is the pro...
You're returning a reference to a local variable. When you exit the function it gets destructed. You need to return a copy: vector<int> Getv() { vector<int> w(10); w[0]=10; cout<<w.size()<<endl; return w; } Or you could make w static: const vector<int>& Getv() { static vector<int> w(10); w[0]=10; cout<...
1,574,367
1,574,433
LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification
I recently converted a multi-project Visual Studio solution to use .dlls instead of .libs for each of the projects. However, I now get a linker warning for each project as stated in the example. MSDN didn't serve to be all that helpful with this. Why is this and how can I solve it? Warning 2 warning LNK4075: ig...
You can either have "Edit and continue" support or optimizations. Usually, you put "Edit and continue" on debug builds, and optimizations on release builds. Edit and continue allows you to change code while you are debugging and just keep the program running. It's not supported if the code also has to be optimized.
1,574,512
1,574,568
Constructor injection
I know the code is missing (Someone will give negative numbers). But I only want to know how do you solve constructor injection in this situation? class PresenterFactory { public: template<class TModel> AbstractPresenter<TModel>* GetFor(AbstractView<TModel> * view) { return new PresenterA(view, new...
Why not to use two constructors? // constructor with one argument ViewA(AbstractPresenter<ModelA> *presenter) : AbstractView<ModelA> (presenter) { } // constructor without arguments ViewA() : AbstractView<ModelA>(factory.GetFor<ModelA>(this)) { } By the way, this pointer is valid only within nonstatic member function...
1,574,517
1,574,956
Calling methods in a win32 service with elevated privileges from an application
I have developed a Win32 C/C++ application that creates dynamic WFP IP filters, however it must be run as admin to do so (due to the Windows security policy). I want to place the code that requires admin privileges in a service running with admin privileges and then call it from the application running as a normal user...
It is certainly the right approach to have a separate executable that has the privilege to perform the action you require, so that the main application can run in a restricted user account. As for sending requests to the service, there is nothing special about the fact it is running as a service. Just consider it to b...
1,574,522
1,574,759
Is there a way to get better information for the context of an error when using msvc? (ex: C2248)
I'm wondering if there is a way to get better information about the location of an error in msvc (2005)? For example, when inheriting from boost::noncopyable in my class I get a C2248 error saying something like: error C2248: 'boost::noncopyable_::noncopyable::noncopyable' : cannot access private member declared in c...
I can confirm with Code::Blocks and VC++ 2005, that it gives no hint where the error occurs. Neither does declaring your own private copy constructor help. #include <boost/noncopyable.hpp> class X: boost::noncopyable { }; void foo(X x) {} int main() { X x; foo(x); } The compile log (line five is the last l...
1,574,647
1,574,903
A way to turn boost::posix_time::ptime into an __int64
Does anyone know if there is a good way to turn a boost::posix_time::ptime into an __int64 value. (I have compiled the microsecond version, not the nanosecond version). I need to do this somehow as I am looking to store the resulting __int64 in a union type which uses the raw data for a high-performance application. ...
Converting a ptime to an integer is rather meaningless, since ptime is an abstraction of the actual time. An integer based time is a representation of that time as a count from an epoch. What you (probably) want to do is generate a time_duration from your time to the epoch you are interested in, then use the time_durat...
1,574,721
1,574,784
g++ doesn't like template method chaining on template var?
I'm trying to compile with g++ some code previously developed under Visual C++ 2008 Express Edition, and it looks like g++ won't let me call a template method on a reference returned by a method of a template variable. I was able to narrow the problem down to the following code: class Inner { public: template<typenam...
could you try with? template<typename T> int do_outer(T& val) { return val.get_inner().template get<int>(); } I don't have access to gcc atm, but I've had similar issues and adding the template keyword always solved them. And it works in VS too.
1,574,773
1,574,974
Is it possible to hijack standard out
I am trying to redirect the stdout of an already running process on Windows XP using C#. I am aware that I can do this if I spawn the process myself, but for this application I would prefer a "listener" i could just attach to another process. Is this possible in pure .Net and if not is it even possible with Win32? Than...
It would be fairly easy to do this in Win32 using the Detours Library. You'd look at all calls to WriteFile, and check whether they were going to standard output. You might also want to look at the console output functions (e.g. WriteConsoleOutput) but they're used rarely enough that you probably don't need to bother f...
1,574,910
1,574,927
C++ map object not growing when members added
Below the map 'widgets' is always size of 1 for some reason. There should be 4 when it's done. Output: Widget: widget_ram_label:layout_bar:0 1 Widget: widget_ram_active:layout_bar:0 1 Widget: widget_ram_total:layout_bar:0 1 Widget: widget_wlan0_label:layout_bar:0 1 Here's widgets: std::map<const char *, Widget *> widg...
Maybe because all your name pointers poitns to the same buffer? Because the content of name changes, but not the value of the pointer to name in the map. Try to use std::string instead. Replace you name buffer by #include <string > //... std::string name = "the name"; and replace your map by std::map< const std::strin...
1,575,003
1,575,522
Direct3D Texture Post-Processing/Copying
So I'm trying to implement some Direct3D post-processing, and I'm having issues rendering to textures. Basically, my program looks like this: // Render scene to "scene_texture" (an HDR texture)... ... device->SetRenderTarget(0, brightpass_surface); device->SetTexture(0, scene_texture); // Render "scene_texture" to "...
The problem was multisampling. In the D3DPRESENT_PARAMS structure, I had enabled multisampling. You can't render from one floating point texture into another floating point texture using the "full-screen quad" technique while multisampling is enabled. Instead, I enabled multisampling in the HDR scene render target ...
1,575,240
1,575,257
Using a std::set in a class?
I am trying to combine using a std::set and a class, like this: #include <set> class cmdline { public: cmdline(); ~cmdline(); private: set<int> flags; // this is line 14 }; but, it doesn't like the set flags; part: cmdline.hpp:14: error: ISO C++ forbids declaration of 'set' with no ty...
You need to use std::set; set is in the std namespace.
1,575,323
1,575,344
How to deal with seniors' bad coding style/practices?
I am new to work but the company I work in hires a lot of non-comp-science people who are smart enough to get the work done (complex) but lack the style and practices that should help other people read their code. For example they adopt C++ but still use C-like 3 page functions which drives new folks nuts when they try...
The best and most important thing you can do is lead by example. Do things the right way and try to improve things slowly. You aren't going to fix anything overnight. Make sure every piece of code that you are responsible for is better after you are done with it. Over time, the system will tangibly be better because...
1,575,460
1,575,754
Is there a cross-platform exec in Boost?
I want to execute a sub-process in C++. I need it to work on Windows and Linux. Is there such a function in Boost? What is the standard way of doing it?
Poco and ACE have Process classes that do what you want. See Foundation->Processes->Process in Poco; Process.h/Process.cpp for Ace. I wouldn't be surprised if QT has something similar. As for how to do it, basically you wrap the OS dependencies and bury the details. Poco and Ace offer contrasting common methods. Po...
1,575,698
1,575,709
std::string and format string
I found the below code through Google. It almost does what I want it to do, except it doesn't provide a way to indicate the precision like '%.*f' does in C-type format strings. Also, it doesn't provide anything further than 5 decimal places. Am I going to have to stick with C strings and snprintf? #include <string> #in...
You want to use the std::setprecision manipulator: int main() { std::cout << std::setprecision(9) << to_string<long>(3.1415926535897931, std::dec) << '\n'; return 0; }
1,575,749
1,575,960
C++ Abstract base class array of ptrs to ptrs
I have an abstract base class (Comparable) with Date and Time virtually inheriting from it and a DateTime class v-inheriting from Date and Time. My problem is this: I was tasked with dynamically allocating an array of Comparables. Comparable ** compArray; compArray = new Comparable *[n]; // where n is user specified nu...
You have to have alternating Dates and Times so you don't need to create the DateTime object, do you? Remember you are sorting an inplace array. From and to are like the begin() and end() parts of the STL containers. void QuickSort(Comparable** from, Comparable** to) { int n = to - from; if (n < 8) BubbleSort(f...
1,575,802
1,597,811
Python callback with SWIG wrapped type
I'm trying to add a python callback to a C++ library as illustrated: template<typename T> void doCallback(shared_ptr<T> data) { PyObject* pyfunc; //I have this already PyObject* args = Py_BuildValue("(O)", data); PyEval_CallObject(pyfunc,args); } This fails because data hasn't gone through swig, and isn't a P...
My first answer misunderstood the question completely, so let's try this again. Your central problem is the free type parameter T in the definition of doCallback. As you point out in your question, there's no way to make a SWIG object out of a shared_ptr<T> without a concrete value for T: shared_ptr<T> isn't really a ...
1,575,838
1,578,009
Embedding Ruby in a C++ application using SWIG?
I've successfully created Ruby-C++ bindings in the past using SWIG where the C++ code was compiled as a dynamic library with the Ruby script connecting to it. However, I'd like to do it the other way around. Create an executable using C++ and enable it to load and execute Ruby code. Ruby should be able to call function...
You may be interested in Ruby embedded into c++
1,575,937
1,575,951
Using a pure C++ compiler versus Visual C++
I searched around for the answers to these questions, but I have had little luck. So, I thought I would post them here to get some clarification. If this is a duplicate, please let me know, and I will close this. Okay, with that said, I would like to begin learning C++. I come from a C# background and I have a great...
The Visual C++ compiler will compile C++ code into standalone EXEs that have nothing to do with the .NET framework. The only way to get the .NET baggage thrown in is to compile the C++ as "managed". If you create a new project (File|New|New Project) Then choose "Win32" from the Visual C++ submenu in the project types a...
1,576,317
1,576,419
Does code in header file increases binary size?
Consider this: class Foo{ void func1(){ /*func1 code*/ } void func2(){ /*func2 code*/ } }; Case 1: class Foo in Foo.h Case 2: class Foo nicely seperated among Foo.h and Foo.cpp Various other cpp files include Foo.h My question is...Will Case 1 lead to a bigger binar...
Maybe it will, maybe it won't. It really has nothing to do with header files. What matters here is that your member functions are defined in the class definition. When member functions are defined like that, they are treated as inline functions. If the compiler decides not to actually inline any calls to these function...
1,576,409
1,576,466
In a makefile, how do I execute a command on each file name in variable?
I know I am doing it wrong, but I can't figure out how to organize this makefile. I define my util source files, and use some functions to define the .o files from them here: UTIL_SRC = utils/src/foo.cpp utils/src/bar.cpp utils/src/baz.cpp UTIL_OBJS = $(patsubst utils/src/%.cpp,utils/obj/%.o,$(UTIL_SRC)) This is the ...
It's usually easier to work with implicit rules. There are a lot of predefined ones, where you'll only need to specify variables. CXX=g++ CXXFLAGS=$(UTIL_FLAGS) Then you need to define an executable, like this myutil: $(UTIL_OBJS) Since you're not storing your objects in the same directory, you'll need to specify a n...
1,576,460
1,576,496
Standard Template String class: string.fill()
I need a way to create a string of n chars. In this case ascii value zero. I know I can do it by calling the constructor: string sTemp(125000, 'a'); but I would like to reuse sTemp in many places and fill it with different lengths. I am calling a library that takes a string pointer and length as an argument and fills t...
The string class provides the method assign to assign a given string a new value. The signatures are 1. string& assign ( const string& str ); 2. string& assign ( const string& str, size_t pos, size_t n ); 3. string& assign ( const char* s, size_t n ); 4. string& assign ( const char* s ); 5. string& assign ( size_t n, c...
1,576,647
1,576,667
Using C++ with Eclipse
I'm figuring out that there's two ways of writing C++ in Eclipse: either download the Eclipse IDE for C/C++ Developers or download the regular Eclipse for java and add the CDT plugin. What is the difference between these two? (Note that I'm already exstensively using Eclipse for Java) Thank you
The C++ tools end up the same so depends if you use Eclipse for other things. If for other things then I would start with the more complex setup e.g. if you do Java J2EE I would download the Eclipse J2EE then add the C++ tools If just C++ start with the Eclipse C++ I also found using the Yoxos/Eclipse Source packaging ...
1,577,084
1,577,228
Storing values of any type as type initially supplied in templated factory method in C++?
This is a slightly different question to this one ([Accessing a method from a templated derived class without using virtual functions in c++?) which I asked recently. I would like to create an instance of an object using a templated factory method, then from then on only be able to set and get a value based on the init...
Your problem with boost::any is that it's too flexible. The basic idea behind it is still sane. What you need to do is wrap the initial value in an object of type template<typename T> class ItemOfType<T> : public Item. Item::create<T> would then return such a typed object. When you later try to assign a U, you first te...
1,577,488
1,577,591
Templated parameter for a template specialisation?
Hi I've got a static member of a templated class that I want defined for a sub group of classes that are templated ie: template <typename T> class FooT { private: static int ms_id; }; template <typename T> class Foo {}; template<> template<typename T> int FooT< template Foo<T> >::ms_id = 10; Sadly this throws the...
You can do this by partially specializing an "initializer template": template <typename T> class FooT { private: static int ms_id; }; template <typename T> class Foo {}; template <typename T> class GetValue { static const int v = 0; }; template <typename T> class GetValue< Foo<T> > { static const int v = 10; ...
1,577,621
1,577,646
Will this regex be enough to remove C++ multiline comments?
I need to parse some C++ files, and to make things easier for me, I thought about removing multiline comments. I tried the following regex : /(\/\*.*?\*\/)/, using the multiline modifier, and it seems to work. Do you think there will be any case where it will fail?
The following is going to hurt you: std::cout << "Printing some /* source code */" << std::endl; This is a kind example. Imagine the damage you could do if the string started a comment and didn't end it? You could end up deleting huge chunks of your code. A regex may give you a good "quick-and-dirty" solution, and may...
1,577,696
1,577,754
Most efficient way to store a mixed collection of doubles and ints
I need to store a collection of ints and doubles (representing nominal and real valued data) in c++. I could obviously store them all in a std::vector<double> , but this feels a bit wrong and doesn't get the aesthetics bonus points. I could also cook up something based on polymorphism, but I also need the collection to...
Is ordering an important point in your container ? If not so: class MyContainer { std::vector<double> doubles; std::vector<int> ints; push(double value) { doubles.push_back(value); } push(int value) { ints.push_back(value); } .... }; The iterator part (to browse the whole container) could be...
1,577,765
1,577,851
Why must a pointer to a char array need strcpy to assign characters to its array and double quotes assignment will not work?
The first example does not work when you go to delete the pointer. The program either hangs when I add the null terminator or without it I get: Debug Assertion Failed Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) from Visual Studio 2008 //Won't work when deleting pointer: char *at = new char [3]; at = "tw"...
Because a char* isn't a string. It's just a pointer to some character, with the convention that there might be more characters to follow and that after the last one there is a '\0'. A string literal in C (and thus in C++) like "abc" is just an array of characters, with the compiler silently adding a '\0'. When you ass...
1,577,940
1,577,960
How to store TypeInfo
class A {} A a; type_info info = typeid (a); // error type_info is private i want a list list<type_info> to store the type of classes. Is there a solution?
You cannot instantiate objects of the type_info class directly, because the class has only a private copy constructor. Since the list needs copy constructor... If you really need it, use std::list< type_info*>. I don't know why you need this list, but I would think to an alternative design, not involving RTTI, if possi...
1,578,006
1,581,581
Qt: TableWidget's ItemAt() acting weirdly
i'm working on a windows application, where in a dialog i query some data from Postgres, and manually show the output in a table widget. m_ui->tableWidget->setRowCount(joinedData.count()); for(int i=0; i<joinedData.count(); i++) //for each row { m_ui->tableWidget->setItem(i, 0, new QTableWidgetItem(joinedData[i...
Try this: QTableWidgetItem* clickedItem = m_ui->tableWidget->itemAt(event->pos()); The problem is that you are trying to map the global position to the table widget position, without considering the scrollable area. To map the global position into something you can pass to itemAt, use tableWidget->viewport()->mapFromG...
1,578,130
1,578,312
how to design system so users can generate their own objects using dlls
I have a server which takes some messages x and outputs some messages Y. Currently the x to y mapping is fixed. So x1 will always generate y1 with corresponding fields. But now I want to be able to make it configurable such that the users can put their own dll which will generate x1 to y2, y3, or however they want. In...
This is not too hard, but you will need to provide an interface header (.h file) to DLL writers. You'll also need to tell them which compiler to use, or use a COM-compatible interface. A quick sketch would be an interface that provides A queryTypesSupported function, provided by the DLL and called by the EXE to determ...
1,578,162
1,578,265
Is there any trick to handle very very large inputs in C++?
A class went to a school trip. And, as usually, all N kids have got their backpacks stuffed with candy. But soon quarrels started all over the place, as some of the kids had more candies than others. Soon, the teacher realized that he has to step in: "Everybody, listen! Put all the candies you have on this table here!...
Easy. Don't add up the number of candies. Instead, keep a count of kids, a count of candies per kid. (CCK), and a count of extra candies (CEC. When you read a new line, CK += 1; CEC += newCandies; if (CEC > CK) CCK += (CEC / CK); CEC %= CK;
1,578,190
1,578,544
Using a QListView or similar effectively in Qt4
I am slowly getting used to using the Qt4 GUI framework. In a project I am working on, I need to be able to add/edit/remove Team objects in a list. Coming from a C#.NET perspective, I would do something like List<Team> teams = new List<Team>(); teamsListBox.DataSource = teams; teamsListBox.DisplayMember = "Name"; Then...
You should have a look at QAbstractItemModel and QStandardItemModel or create a customized TeamItemModel class for your teams that inherits from QAbstractItemModel. Those customized class will manage how the items are displayed in the Widget like QListView. A simple for QString item example with QStringList: QStringLi...
1,578,215
1,578,354
Exporting template code = dangerous? (MSVC)
As I noted in another SO question, I came across this article. The issue came up when I compiled boost 1.40 via MSVC7.1 and several C4251 warnings popped up. Now, after reading said article, I wonder: Is it generally discouraged to export template code, e.g. class DLLEXPORT_MACRO AClass { public: std::vector<int> ge...
This appears to be a bad idea, as std::vector differs or might differ between compiler versions. However, this can likely fail at load time, because the name mangling of std::vector should differ across compiler versions (that's part of the rationale for name mangling). This link-time failure is something you can't rea...
1,578,635
1,578,652
Declaring a global in a global header file?
I have a header file, lets say Common.h, that is included in all of the files over several projects. Basically i want to declare a global variable, e.g.: class MemoryManager; DLL_EXPORT MemoryManager* gMemoryManager; When i do this i get tons of linker errors saying class MemoryManager* gMemoryManager is already defin...
As it is you are creating a separate copy of the variable in each compiled file. These are then colliding at the linking stage. Remember that the preprocessor reads in all the header files and makes one big file out of all of them. So each time this big file is compiled, another identical copy of gMemoryManager is crea...
1,578,703
1,578,767
variable + value macro expansion
I tried without any result. My code looks like this: #include "stdafx.h" #include <iostream> #define R() ( rand() ) #define H(a,b) ( a ## b ) #define S(a) ( # a ) #define CAT() H(S(distinct_name_), R()) int main(int argc, _TCHAR* argv[]) { std::cout << CAT() << std::endl; std::cout << CAT() << std::endl; ...
I see that a lot of people have already correctly answered this question, but as an alternative suggestion, if your preprocessor implements __TIME__ or __LINE__ you could get a result quite like what you want, with a line number or time concatenated, rather than a random number.
1,578,714
1,578,764
One class with multiple implementation files
Is there anything wrong with having a single class (one .h) implemented over multiple source files? I realize that this could be a symptom of too much code in a single class, but is there anything technically wrong with it? For instance: Foo.h class Foo { void Read(); void Write(); void Run(); } Foo.Read.cpp ...
This is fine. In the end, it will be all linked together. I have even seen code, where every member function was in a different *.cpp file.
1,578,829
1,578,848
Cannot open include file "AIUtilities.h": No such file or directory. But it exists?
I have a two projects, AI and Core, which used to hold a circular dependency. I have a CoreUtilities file that I have broken up to remove this dependency, and added the functions I have removed to a new file called AIUtilities(.cpp/.h). I then went to the piece in my AI project that uses these functions and added #i...
Did you update your project settings with the path to the direcory containing AI/AIUtilities? Update: From the solution explorer window, right click on your project and choose "properties" then a new windows "your_project_name property page" will pop up. In this window on the left pane you'll see a tree. Click on 'Con...
1,578,950
1,578,968
The procedure entry point could not be located in the dynamic link library Core.dll
I am converting my project to use DLLs and am trying to break apart my Singleton class to avoid using templates. My class, LudoMemory, originally inherited from Singleton. I am trying to give it the functions to destroy and create itself now and have my main engine not rely on the Singleton. I have written a simple ...
you don't have multiple versions of ludocore.dll on your system, do you? Procedure entry points errors usually mean: you compiled your project against ludocore.lib version x, and when running the program, it uses ludocore.dll version y, and version y does not define LudoMemory::Destroy().
1,579,007
1,589,683
How can I include a subset of a .cpp file in a Doxygen comment?
I'm trying to write some Doxygen comment blocks, and I'd like to include example snippets of code. Of course, I'd like the examples to actually compile so they don't get stale. My example.cpp (that I \include in the .h file) looks like this: #include "stdafx.h" #include "../types_lib/Time_Limiter.h" #include <vector>...
EDITED to add 2nd arg to clip macro. Here's what I've done, which seems to work for me. Mostly taken from hint from EricM.... my source file Time_Limiter_example.cpp is: #include "stdafx.h" #include "../types_lib/Time_Limiter.h" #include <vector> void tl_demo () { // scarce will be a gate to control some resourc...
1,579,086
1,579,533
Why does ofstream sometimes create files but can't write to them?
I'm trying to use the ofstream class to write some stuff to a file, but all that happens is that the file gets created, and then nothing. I have some simply code here: #include <iostream> #include <fstream> #include <cstring> #include <cerrno> #include <time.h> using namespace std; int main(int argc, char* argv[]) ...
Just a thought :- in your real code are you re-using your stream object? If so, you need to ensure that you call clear() on the stream before re-using the object otherwise, if there was a previous error state, it won't work. As I recall, not calling clear() on such a stream would result in an empty file that couldn'...
1,579,154
1,579,328
ASSERT fails on CDC SelectObject() call - What can I try?
I'm working on a multi-threaded win32 MFC application. We are rendering a map and displaying it in a pane in the user interface along with custom-rendered objects on top. It's slow to render (~800 ms), which is happening on the User Interface thread. I'm trying to move the rendering onto its own thread so that the me...
Golden. The mapping between handles and objects are in thread-local storage. In a multi-threaded environment because windows are owned by threads, MFC keeps the temporary and permanent window handle map in thread local storage. The same is true for other handle maps like those for GDI objects and device c...
1,579,232
1,579,264
C++ Get object type at compile time, e.g., numeric_limits<typeof<a>>::max()?
Given int a;, I know that the following returns the largest value that a can hold. numeric_limits<int>::max() However, I'd like to get this same information without knowing that a is an int. I'd like to do something like this: numeric_limits<typeof<a>>::max() Not with this exact syntax, but is this even possible us...
numeric_limits is what is known as a type trait. It stores information relative to a type, in an unobtrusive way. Concerning your question, you can just define a template function that will determine the type of the variable for you. template <typename T> T valued_max( const T& v ) { return numeric_limits<T>::max(); ...
1,579,273
1,579,518
How would you solve this math equation for x in C++/C
Solve this equation for x, (1 + x)^4=34.5 . I am interested in the math libraries you'd use. the equation is MUCH SIMPLER (1 + x)^4=34.5 thanks
approximate x*(x+a)^b=c You'll need a more robust solution for more complex polynomials, but this may be good enough to finish your homework. This algorithm uses Newton's Method and is written in Ruby. You can verify that the derivative and answer is correct using wolfram|alpha. def f(x,a,b,c) return x*(x+a)**b-c end...
1,579,357
1,587,913
Heap currupted error in VS2005 with OpenCV?
I'm getting an error called, "corruption of the heap" when I try to debug this simple code, CvCapture* capture = cvCaptureFromFile("1.avi"); if( capture ) { cvNamedWindow( "Motion", 1 ); while(true) { //Grab the frame and display the ima...
This likely means that OpenCV can't load the AVI. I always convert my videos to RAW I420 format; this loads perfectly. The following command will convert a video to this format using MEncoder: mencoder -ovc raw -nosound -vf format=i420 -o "%OUTPUT%" "%INPUT%" where %INPUT% and %OUTPUT% are the input and output files.
1,579,391
1,579,434
Static Global Fields in a Shared Library - Where do they go?
I have a cpp file from which I am generating a shared library (using autofoo and the like). Within the cpp file, I have declared a couple of static fields that I use throughout the library functions. My question is 2-part: 1) Where are these fields stored in memory? It's not as if the system instantiates the entire l...
The code used to load shared libraries: Generally (each has minor technical differences): Loads the shared lib into memory Walks the symbol table and updates the address of function in the DLL Initializes any global static members using their constructor. Note: The shared lib loader need not do all this at the load p...
1,579,426
1,590,115
CMake Visual Studio linking executable with static library
I have a very simple (currently just a main.cpp) CMake C++ project that I'm trying to build on both Mac OS X and Windows. It depends on libgsasl, which I have compiled as a static library on both platforms. Mac OS X has no problems building, and Windows doesn't complain during the build either and produces an EXE. When...
In the MS tool chain, a .lib can either be static library or an import library to the actual DLL. You can use dumpbin to peek inside the library to see the actual type it is. There are a couple of different ways to handle the details, but my preferred technique is to use the /summary option. An import library will ha...
1,579,487
1,579,501
C++ initializing the dynamic array elements
const size_t size = 5; int *i = new int[size](); for (int* k = i; k != i + size; ++k) { cout << *k << endl; } Even though I have value initia...
My first thought is: "NO...just say NO!" Do you have some really, truly, unbelievably good reason not to use vector? std::vector<int> i(5, 0); Edit: Of course, if you want it initialized to zeros, that'll happen by default... Edit2: As mentioned, what you're asking for is value initialization -- but value initializat...
1,579,492
1,588,191
pimpl idiom and template class friend
I'm trying to use the pimpl idiom to hide some grungy template code, but I can't give derived classes of the body class friend access to the handle class. I get an error C2248 from MSVC 9 sp1. Here's some code to duplicate the error: // // interface.hpp // namespace internal{ template<class T> class specific_...
Well, I was able to "solve" this problem by making the body a public declaration in the interface. That solves the C2248 error during the declaration of the specific_body. I also made the body a friend to the interface class and added a method to the body struct: static interface create( body *pbody ) { return in...
1,579,521
1,579,540
Converting a C-string to a std::vector<byte> in an efficient way
I want to convert a C-style string into a byte-vector. A working solution would be converting each character manually and pushing it on the vector. However, I'm not satisfied with this solution and want to find a more elegant way. One of my attempts was the following: std::vector<byte> myVector; &myVector[0] = (byte)"M...
The most basic thing would be something like: const char *cstr = "bla" std::vector<char> vec(cstr, cstr + strlen(cstr)); Of course, don't calculate the length if you know it. The more common solution is to use the std::string class: const char *cstr; std::string str = cstr;
1,579,532
1,587,015
Create from scratch, or build up on Scratch?
I'm considering building a visual programming language, akin to Scratch, for use by children (a.k.a. poor typists) in programming micro-controllers or robots. There is, for example, a project to build a graphical programming environment for the Arduino. I really like Scratch, and would like the graphical coding to be...
If you are familiar with C/C++ then its worth learning QT. It should be easy for you to pick up and get going in no time. There are also plenty of examples that come with the package to get you started once you install it. From there you will be able to evaluate how best it can work for you.
1,579,663
1,579,671
Does copying the content of one array to another cause a memory leak
Does this code cause a memory leak: int main(){ int * a = new int[10]; int * b = new int[10]; for(int i = 0 ; i < 10; i++) { a[i] = 1; b[i] = 1; } for(int i = 0 ; i < 10; i++) { a[i] = b[i]; //each a[i] is allocated 4 bytes on heap //when we copy b[i] int...
No, there's no leak there. You're just copying values within the array. Think of the arrays as two banks of lockers in a changing room - you're just copying what's in one locker and putting it in a locker in the other bank; the locker itself stays where it is.
1,579,688
1,579,702
Can c++ create array of pointers to different classes dynamically loaded from dll?
Can c++ create array of pointers to different classes dynamically loaded from dll? ps.without headers with class definations
I think you need to have an exported function that instantiates objects of the class. Then you can, of course, put these values into array.
1,579,711
1,579,734
Optional parameter for reference to pointer?
How do I declare the second parameter as optional? template <typename T> inline void Delete (T *&MemoryToFree, T *&MemoryToFree2 = ){ delete MemoryToFree; MemoryToFree = NULL; delete MemoryToFree2; MemoryToFree2 = NULL; } I tried several things after the = operator, like NULL, (T*)NULL etc. Can t...
You could just overload the function template <typename T> inline void Delete (T *&MemoryToFree){ delete MemoryToFree; MemoryToFree = NULL; } template <typename T, typename T2> inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){ delete MemoryToFree; MemoryToFree = NULL; ...
1,579,719
1,579,732
Variable number of parameters in function in C++
How I can have variable number of parameters in my function in C++. Analog in C#: public void Foo(params int[] a) { for (int i = 0; i < a.Length; i++) Console.WriteLine(a[i]); } public void UseFoo() { Foo(); Foo(1); Foo(1, 2); } Analog in Java: public void Foo(int... a) { for (int i = 0; i...
These are called Variadic functions. Wikipedia lists example code for C++. To portably implement variadic functions in the C programming language, the standard stdarg.h header file should be used. The older varargs.h header has been deprecated in favor of stdarg.h. In C++, the header file cstdarg should be...
1,579,786
1,579,813
Are array of pointers to different types possible in c++?
Are array of pointers to different types possible in c++? with example please)
C++ is C with more stuff. So if you want to do it the C way, as above you just make an array of void pointers void *ary[10]; ary[0] = new int(); ary[1] = new float(); DA. If you want to do things the object oriented way, then you want to use a collection, and have all the things you going to be adding to the collecti...
1,579,809
1,589,663
MATLAB engine versus libraries created by MATLAB Compiler?
To call MATLAB code in C or C++, how do you choose between using the MATLAB engine and using the MATLAB Compiler mcc to create C or C++ shared libraries from your MATLAB code? What are their pros and cons? For the second method, see http://www.mathworks.com/access/helpdesk/help/toolbox/compiler/f2-9676.html Are there o...
If the computation is linear and long, I would use mcc to compile the code. It is as if MATLAB was simply another library with numerical routines in it to be linked into your program. If I wanted to provide interaction with MATLAB in my program, where the user could specify any of a large number of statements that wou...
1,579,873
1,580,132
Benefits of Parallel programming
I have three similar questions: Which known applications have benefits of multicore processors? Which known applications use posix threads (pthreads)? What can pthreads do that Java threads cannot?
Answer to first two questions: most Linux open source projects written in C use pthreads. For example Apache. What can pthreads do that java threads cannot? They can work without Java Virtual Machine.
1,579,928
1,579,980
C++ functor - unexpected behaviour?
I have written this program, which sorts some ints using a functor: #include<iostream> #include<list> #include<set> using namespace std; struct IntSorter { unsigned int comparisons; IntSorter() { std::cout << "new intsorter" << std::endl; comparisons = 0; } bool operator() (const ...
You're not really doing anything wrong. The problem lies entirely in your expectation -- the sorter is passed by value, so there's a bare minimum of one copy made as you pass it. The sort function is free to make more copies as well (e.g. a recursive sort will probably pass a copy to each recursive invocation). There's...
1,579,981
1,580,014
l-value substr method in C++
I want to create a substr method in C++ in a string class that I made. The string class is based on C-style string of course, and I take care of the memory management. I want to write a substr(start, length) function that can work on the regular way: CustomString mystring = "Hello"; cout << mystring.substr(0,2); // wi...
To support that, you'll probably have to write your substr() to return a proxy object that keeps track of what part of the original string is being referred to. The proxy object will overload operator=, and in it will replace the referred-to substring with the newly assigned one. Edit in response to comments: the idea ...