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 |
|---|---|---|---|---|
3,020,146 | 3,021,579 | resources for embedded projects | Can anyone suggest links/resources for sample project implementations of embedded projects using c++ or gcc.
| Many resources are target specific, so you will have to be more specific if you want a specific answer. However http://embedded.com/ is a good general resource, and depending on your geographical location, you may qualify for a free subscription to Embedded Systems Design or Embedded Systems Design Europe paper public... |
3,020,255 | 3,020,296 | Using new to allocate an array of class elements with an overloaded constructor in C++ | As an example say I have a class foo that does not have a default constructor but one that looks like this
foo:foo(int _varA,int _varB)
{
m_VarA = _varA;
m_VarB = _varB;
}
How would I allocate an array of these.
I seem to remember trying somthing like this unsuccessfully.
foo* MyArray = new foo[100](25,14).
I d... | If you are to be able to allocate an array of a class (directly, using new[]), the class must have a default constructor. No default constructor, no dynamic arrays.
|
3,020,274 | 3,043,388 | Can I write a test that succeeds if and only if a statement does not compile? | I'd like to prevent clients of my class from doing something stupid. To that end, I have used the type system, and made my class only accept specific types as input. Consider the following example (Not real code, I've left off things like virtual destructors for the sake of example):
class MyDataChunk
{
//Look Ma! ... | With the latest clarification the problem is simple:
void foo(Filter*);
void foo(Sorter*);
template<typename T> void test() {
foo((T*)NULL);
}
If anyone passes a class that's both a Filter and a Sorter, the overload resolution is ambiguous.
|
3,020,316 | 3,020,328 | What VS 2010 Template to Chose? | I am just getting started with C++ and wanted to know does it really matter what template you chose in Visual Studio 2010 (for creating executables)? Like if I was creating a console application there is CLR Console Application, Win32 Console Application, and Win32 Project (description says it can be an application or ... | If you are learning the C++ language itself, you probably want just a console based application. It means basically that you will have a black window that pops up and you can use things like std::cout to output to standard output and std::cin to get input from that console as well.
You probably do not want the CLR con... |
3,020,425 | 3,020,520 | C++ Multiple inheritance with interfaces? | Greetings all,
I come from Java background and I am having difficulty with multiple inheritance.
I have an interface called IView which has init() method.I want to derive a new class called PlaneViewer implementing above interface and extend another class. (QWidget).
My implementation is as:
IViwer.h (only Header file ... |
Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView?
You do not have to declare init() in PlaneViewer, but if you don't PlaneViewer will be an abstract class, meaning that you cannot instantiate it.
If you mean to ask if you have to have 'void init();' in th... |
3,020,441 | 3,020,469 | Academic question: typename |
Possible Duplicate:
Why do I need to use typedef typename in g++ but not VS?
Hi, recently I accounted with a "simple problem" of porting code from VC++ to gcc/intel.
The code is compiles w/o error on VC++:
#include <vector>
using std::vector;
template <class T>
void test_vec( std::vector<T> &vec)
{
typed... | Here is a page that explains typename.
|
3,020,584 | 3,020,589 | Avoid warning 'Unreferenced Formal Parameter' | I have a super class like this:
class Parent
{
public:
virtual void Function(int param);
};
void Parent::Function(int param)
{
std::cout << param << std::endl;
}
..and a sub-class like this:
class Child : public Parent
{
public:
void Function(int param);
};
void Child::Function(int param)
{
;//Do not... | In C++ you don't have to give a parameter that you aren't using a name so you can just do this:
void Child::Function(int)
{
//Do nothing
}
You may wish to keep the parameter name in the declaration in the header file by way of documentation, though. The empty statement (;) is also unnecessary.
|
3,020,725 | 3,020,749 | char array to LPCTSTR | May I know how I can perform the following conversion?
// el.strCap is char[50]
// InsertItem is expecting TCHAR pointer (LPCTSTR)
// How I can perform conversion?
// I do not have access in both "list" and "el" source code
// Hence, there is no way for me to modify their signature.
list.InsertItem(i, el.strCap);
And ... | If you're using ATL, then you can use the various macros and helper classes that it includes to do the conversion:
char *test = "Hello World";
CA2CT ct(test);
list.InsertItem(i, ct);
Though saying WideCharToMultiByte is too cumbersome is a bit disingenious, in my opinion. It's easy enough to wrap a call to WideCharToM... |
3,020,763 | 3,021,408 | why parent window don't get notifications from child combobox? | I create a simple window with a comboboxex (with inserting few bitmaps), I need to know when user has selected an item from combo-box(I need CBEN_ENDEDIT I think). But Parent window don't get any WM_NOTIFY from that combo-box except one value. Can anyone help me with this please? Why I can't get the notifications ?
//... | What you probably want is CBN_SELCHANGE.
From MSDN:
The CBN_SELCHANGE notification message is sent when the user changes the current selection in the list box of a combo box. The user can change the selection by clicking in the list box or by using the arrow keys. The parent window of the combo box receives this notif... |
3,020,767 | 3,022,127 | Obtaining MFC Feature Pack GUI elements in .NET WinForms | The MFC Feature Pack (and VS 2010) adds out-of-the-box support for several "modern" GUI elements (such as MDI with tabbed documents, the ribbon, and a Visual Studio-style interface with docking panels). These are a boon to those of us that have to support legacy MFC-based applications and want to update their look-and-... | Most of these features are provided to .NET developers through WPF, not WinForms. Nothing is going to meet your expectation of "should be available by now in WinForms" because WinForms is not being added to. Like COM before it, "it's not dead, but it's done".
I think you have your answer in your question. If you're mai... |
3,020,913 | 3,020,949 | Shift count negative or too big error - correct solution? | I have the following function for reading a big-endian quadword (in a abstract base file I/O class):
unsigned long long File::readBigEndQuadWord(){
unsigned long long qT = 0;
qT |= readb() << 56;
qT |= readb() << 48;
qT |= readb() << 40;
qT |= readb() << 32;
qT |= readb() << 24;
qT |= readb() << 16;
qT ... | Your way of removing the warning is correct. As you probably do already know, the warning is occurring because you're trying to shift the contents of a byte beyond the boundaries of a word, then store it in the quadword. This operation is undefined. (It will evaluate the right-side of the assignment before assigning th... |
3,021,134 | 3,512,429 | GCC/XCode equivalent of _CrtCheckMemory? | When dealing with random memory overwrites, in MSVC it is possible to validate the state of the heap at various points with a call to _CrtCheckMemory, and know with at least a small level of confidence that the code up until the check was not responsible for any errors that might cause new or malloc to fail later.
In X... | This feature IS actually built into the heap in GCC.
As described here
The easiest way to enable it is on the XCode::Run menu: Enable Guard Malloc
|
3,021,333 | 3,022,238 | Can I use memcpy in C++ to copy classes that have no pointers or virtual functions | Say I have a class, something like the following;
class MyClass
{
public:
MyClass();
int a,b,c;
double x,y,z;
};
#define PageSize 1000000
MyClass Array1[PageSize],Array2[PageSize];
If my class has not pointers or virtual methods, is it safe to use the following?
memcpy(Array1,Array2,PageSize*sizeof(MyClass));... | According to the Standard, if no copy constructor is provided by the programmer for a class, the compiler will synthesize a constructor which exhibits default memberwise initialization. (12.8.8) However, in 12.8.1, the Standard also says,
A class object can be copied in two
ways, by initialization (12.1, 8.5),
in... |
3,021,377 | 3,021,399 | How can I use Boost::regex.hpp library in C++? | I tried to use Boost library but I failed, see my code:
#include "listy.h"
#include <boost/regex.hpp>
using namespace boost;
ListyCheck::ListyCheck() {
}
ListyCheck::~ListyCheck() {
}
bool ListyCheck::isValidItem(std::string &__item) {
regex e("(\\d{4}[- ]){3}\\d{4}");
return regex_match(__item, e);
}
Wh... | Those are linker errors. The Boost regex library is not a header-only library like shared_ptr (for example) - you need to link against the .a or .lib or whatever binary library.
|
3,021,441 | 4,742,879 | Events with QGraphicsItemGroup | In my application I want to use QGraphicsItemGroup for grouping items into one item.
I played with it a little and not sure using it because when I want to catch events, events are merged together but I want to handle specific event with specific child.
How can I achieve this?
| You need to call QGraphicsItemGroup::setHandlesChildEvents(false). This stops the QGraphicsItemGroup trying to handle the event, and lets the child QGraphicsItems handle them instead.
|
3,021,535 | 3,027,682 | does windows 7 bluetooth stack and API support connection of headsets | We need to write code to search for, pair and connect to a bluetooth headset with Windows 7 Embedded.
Once connected the headset will be used as a normal windows audio device.
We fully control what software is installed on the system so conflicting stacks and similar concerns are not a problem. We would however like... | Windows 7 does not contain an in-box driver for BT audio, however if you pair an audio device an audio driver should be available from windows update.
|
3,021,558 | 3,021,781 | How to best use GCC with Visual Studio | I know this thread
GCC with Visual Studio?
but to me it seems that everything mentioned there is rather outdated and it seems to be the tenor is: don't do it
Who knows a better step by step explanation
thank you in advance
Oops
| Well, unfortunately there is still no plugin for Visual Studio. Using makefiles seems to still be the best idea and there are several tools to automate their building.
As far as I remember, the best tool for this that I've used is Makefile Wizard, which allows almost automatic VC project to makefile converting. Also to... |
3,021,560 | 3,021,575 | Do not properly deleted pointers fragment memory? | That's basically the question. If I have a pointer int *a = &someIntVar and I do not delete it over the course of the program, does it stay in memory after the program has terminated? Is this a case of data fragmentation?
EDIT:
My mistake for using a bad example. So int *a = new int[100]; never gets deleted, and even... | Since you have not newed this pointer, you are not leaking memory.
Were you to do int* a = new int; and not delete a, then you would leak a.
As a rule of thumb, the number of news should equal the number of deletes.
When someIntVar goes out of scope, the stack is unwound and its memory will be freed and a will be left ... |
3,021,572 | 3,021,632 | Two phase Construction in C++ | I have as part of assignment to look into a development kit that uses the "two-phase" construction for C++ classes:
// Include Header
class someFubar{
public:
someFubar();
bool Construction(void);
~someFubar();
private:
fooObject _fooObj;
}
In the source
// someFubar.cpp
someFubar::someFubar : _fooObj(... | A document about Two Phase Construction.
The idea is that you cannot return a value from a constructor to indicate failure. The only way to indicate constructor failure is to throw an exception. This is not always desirable, not least because exception safety is a very complex topic.
So in this case the construction... |
3,021,854 | 3,022,248 | Signals and threads - good or bad design decision? | I have to write a program that performs highly computationally intensive calculations. The program might run for several days.
The calculation can be separated easily in different threads without the need of shared data.
I want a GUI or a web service that informs me of the current status.
My current design uses BOOST::... |
Is this combination of signals and
threads a wise idea? I another forum
somebody advised someone else not to
"go down this road".
It seems to be sound. Can you provide a link to the other thread? Were they explaining their reasoning?
Are there potential deadly pitfalls nearby that I failed to see?
If they are... |
3,021,896 | 3,021,931 | Redundant code in exception handling | I've a recurrent problem, I don't find an elegant solution to avoid the resource cleaning code duplication:
resource allocation:
try {
f()
} catch (...) {
resource cleaning code;
throw;
}
resource cleaning code;
return rc;
So, I know I can do a temporary class with cleaning up destructor, but I don't really li... | You might want to have a look at boost::scope_exit:
http://www.boost.org/doc/libs/1_39_0/libs/scope_exit/doc/html/index.html
|
3,021,991 | 3,022,025 | Template Parameter Initialization | I wrote some C++ code in which I used Templates. Since I used templates, I could not initialize a couple of template class variables. I got an warning message from valgrind saying Conditional jump or move depends on uninitialized value(s). So is there a way to get around this and/or initialize template variables?? I c... | This is just a guess what you are asking about, so please ignore it if it's wrong.
IIUC, your problem is that, with template parameters, you cannot properly default-initialize built-ins and user-defined types. The way to solve this is:
T obj = T();
This works for both built-ins and UDTs.
|
3,022,087 | 3,022,130 | Avoiding 'Buffer Overrun' C6386 warning | In my code, I am using an array xyz of 10 objects. When I am trying to access an element of the array using an unsigned int index like this: xyz[level], I get 'Buffer overrun' warning. Logically, I am pretty sure that level won't exceed 10. How to avoid this warning?
| I'm probably teaching my grandmother to suck eggs here, but do remember that "level won't exceed 10" is wrong for an array of size 10:
char a[10];
a[10] = '\0'; // Bug, and "Buffer Overrun" warning.
|
3,022,220 | 3,022,402 | C++ const-reference semantics? | Consider the sample application below. It demonstrates what I would call a flawed class design.
#include <iostream>
using namespace std;
struct B
{
B() : m_value(1) {}
long m_value;
};
struct A
{
const B& GetB() const { return m_B; }
void Foo(const B &b)
{
// assert(this != &b);
m_B.m_value += b.m_value;
... |
Obviously, the programmer is fooled by the constness of b
As someone once said, You keep using that word. I do not think it means what you think it means.
Const means that you cannot change the value. It does not mean that the value cannot change.
If the programmer is fooled by the fact that some other code else can... |
3,022,356 | 3,022,418 | Constructor Overload Problem in C++ Inheritance | Here my code snippet:
class Request
{
public:
Request(void);
………..
}
Request::Request(void)
{
qDebug()<<"Request: "<<"Hello World";
}
class LoginRequest :public Request
{
public:
LoginRequest(void);
LoginRequest(QDomDocument);
……………
}
LoginRequest::LoginRequest(void)
{
qDebug()<<"LoginRequest: "<<"Hello World"... | The code is not doing what you probably think it is doing. The line:
LoginRequest::LoginRequest();
constructs a temporary object which is immediately destroyed. as others have suggested, you can put duplicate code in a private function, but this has a lot of issues - specifically, such a function can only perfor... |
3,022,457 | 3,022,825 | Nested namespaces, correct static library design issues | I'm currently in the process of developing a fairly large static library which will be used by some tools when it's finished. Now since this project is somewhat larger than anything i've been involved in so far, I realized its time to think of a good structure for the project. Using namespaces is one of those logical ... | Well, I would think that in the core.h header, you would have stuff like
#include <string>
#include <iostream>
namespace core
{
typedef std::string mystring;
#define mycout std::cout
}
And not one using directive, to prevent contaminating the global namespace. In a utils.h header, you would use stuff like:
#in... |
3,022,494 | 3,046,012 | How to apply an mpl::transform to an mpl::string? | I'm trying to apply a transformation to an mpl::string, but can't get it to compile. I'm using MS VC++2010 and Boost 1.43.0. The code:
#include <boost/mpl/string.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/arithmetic.hpp>
using namespace b... | Turns out that it works if I use transform_view.
|
3,022,552 | 3,022,579 | Is there any "standard" htonl-like function for 64 bits integers in C++? | I'm working on an implementation of the memcache protocol which, at some points, uses 64 bits integer values. These values must be stored in "network byte order".
I wish there was some uint64_t htonll(uint64_t value) function to do the change, but unfortunately, if it exist, I couldn't find it.
So I have 1 or 2 questio... | You are probably looking for bswap_64 I think it is supported pretty much everywhere but I wouldn't call it standard.
You can easily check the endianness by creating an int with a value of 1, casting your int's address as a char* and checking the value of the first byte.
For example:
int num = 42;
if(*(char *)&num == ... |
3,022,572 | 3,022,698 | Python equivalent of C++ getline() | In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimite... | Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line?
If the former, try looping raw_input() until something is written that tells it to stop:
lines = []
while True:
user_input = raw_input()
if user_input.strip() == "": #... |
3,022,729 | 3,022,826 | Linking a template class using another template class (error LNK2001) | I implemented the "Strategy" design pattern using an Abstract template class, and two subclasses. Goes like this:
template <class T>
class Neighbourhood {
public:
virtual void alter(std::vector<T>& array, int i1, int i2) = 0;
};
and
template <class T>
class Swap : public Neighbourhood<T> {
public:
virtual void... | It seems it was a pretty rookie mistake. Since Neighbourhood is an abstract class, I must use it always as a pointer (EDIT: or a reference), since it must never be instantiated.
Changed signatures and it worked fine.
EDIT: Also, thanks to Neil, I know "it's got to be in the header".
|
3,022,910 | 3,370,023 | Function lfit in numerical recipes, providing a test function | I am trying to fit collected data to a polynomial equation and I found the lfit function from Numerical Recipes. I only have access to the second edition, so am using that.
I have read about the lfit function and its parameters, one of which is a function pointer, given in the documentation as
void (*funcs)(float, f... | I have since switched to the 3rd edition of NR which has a more understandable routine.
|
3,023,034 | 3,024,495 | Can you call a CLR Injection into SQL Server from C++? | Does anybody know if you can you call a CLR Injection into SQL Server from C++?
| You need to compile your C++ project with /CLR option and use C++/CLI to invoke your CLR Injection code. Certainly that makes your C++ project dependent on .NET Framework.
|
3,023,160 | 3,023,221 | Save OpenGL output with Alpha? | Right now I'm drawing a cube with OpenGL, I'm using Windows and WGL context. I have blending enabled so my cube looks semi transparent. Basically the background == the clear color (Black). I'd like to be able to save the image in raw RGBA format which I can then make into a png. I basically want the cube to blend in wi... | Just draw the cube, setting the clear color to (0, 0, 0, 0), and save the output using glReadPixels.
|
3,023,643 | 3,023,658 | Static struct in C++ | I want to define an structure, where some math constants would be stored.
Here what I've got now:
struct consts {
//salt density kg/m3
static const double gamma;
};
const double consts::gamma = 2350;
It works fine, but there would be more than 10 floating point constants, so I doesn't want to wrote 'static c... | Use a namespace rather than trying to make a struct into a namespace.
namespace consts{
const double gamma = 2350;
}
The method of accessing the data also has exactly the same synatx. So for example:
double delta = 3 * consts::gamma;
|
3,023,760 | 3,023,811 | C++ template specialization | I have a class
template <typename T>
class C
{
static const int K=1;
static ostream& print(ostream& os, const T& t) { return os << t;}
};
I would like to specialize C for int.
//specialization for int
template <>
C<int>{
static const int K=2;
}
I want the default print method that works fo... | You could do it like this:
template <typename T>
class C {
static const int K;
static ostream& print(ostream& os, const T& t) { return os << t;}
};
// general case
template <typename T>
const int C<T>::K = 1;
// specialization
template <>
const int C<int>::K = 2;
|
3,023,770 | 3,023,893 | Is "} while (0);" always equal to "break;} while (1);"? | I have compared gcc assembler output of
do {
// some code
} while (0);
with
do {
// some code
break;
} while (1);
The output is equal, with or without optimization but..
It's always that way?
No experiment can prove theories, they can only show they are wrong
| There is a slight difference:
do {
// code
if ( condition )
continue;
// code
break;
} while(1);
Will restart the loop when condition is true, whereas in the } while(0); version, the continue will be equivalent to break.
If no continue is present, then they should produce exactly the same code.
|
3,023,775 | 3,024,538 | Resources for setting up a Visual Studio/C++ development environment | I haven't done much "front-end" development in about 15 years since moving to database development. I'm planning to start work on a personal project using C++ and since I already have MSDN I'll probably end up doing it in Visual Studio 2010. I'm thinking about using Subversion as a version control system eventually. Of... | I would also like a good answer to this question. What I've done is set it up so that each solution makes reference to a $(SolutionDir)\build directory for includes and libraries. That way each project that has dependencies on other projects can access them and versions won't compete. Then there are post-build comma... |
3,023,909 | 3,023,939 | What is the trick in pAddress & ~(PAGE_SIZE - 1) to get the page's base address | Following function is used to get the page's base address of an address which is inside this page:
void* GetPageAddress(void* pAddress)
{
return (void*)((ULONG_PTR)pAddress & ~(PAGE_SIZE - 1));
}
But I couldn't quite get it, what is the trick it plays here?
Conclusion:
Personally, I think Amardeep's explanation pl... | What it does is clears the bits of the address that fit within the mask created by the page size. Effectively it gets the first valid address of a block.
PAGE_SIZE must be a power of 2 and is represented by a single bit set in the address.
The mask is created by subtracting one from PAGE_SIZE. That effectively sets a... |
3,023,955 | 3,024,025 | Building WM C++ project outside an IDE | I'm wondering if there is some comprehensive tutorial or someone of you can help me solve this problem.
I need to build Windows mobile project written in C++ but I need to do so outside of any IDE. So I would be very grateful if someone could direct me, thank you.
| Well you can call devenv directly with the /build switch and pass it the project name and it will build without opening the IDE. Or do you want to be able to build without an IDE even installed? In that case you could write an msbuild script that would do it.
|
3,024,110 | 3,024,154 | Why compile + link when build a C++ code, instead of generating executable directly | I was asked of this question when mentor an entry-level programmer, I was thinking of this compile + link process so official and usual that I never think about why.
One thing I could think of is to improve the development productivity, but should there be any other more compiler-related reasons?
| Efficiency.
When you compile a program you create an object file for each source file, if you change a source file you only need to recompile that module and then relink (relinking is cheap).
If the compiler did everything in one pass it would have to recompile everything for every change.
It also fits with the unix ph... |
3,024,136 | 3,027,877 | Link compatibility between C++ and D | D easily interfaces with C.
D just as easily interfaces with C++, but (and it's a big but) the C++ needs to be extremely trivial. The code cannot use:
namespaces
templates
multiple inheritance
mix virtual with non-virtual methods
more?
I completely understand the inheritance restriction. The rest however, feel like... | FWIW Qt has an actively developed binding for D: http://www.dsource.org/projects/qtd
I think many components in boost are too highly tied to C++ to be portable meaningfully to other languages.
Using e.g. std::vector is possible if you spend the time on writing regular (e.g. namespace-level) functions that forward to th... |
3,024,197 | 3,024,202 | What does int argc, char *argv[] mean? | In many C++ IDE's and compilers, when it generates the main function for you, it looks like this:
int main(int argc, char *argv[])
When I code C++ without an IDE, just with a command line compiler, I type:
int main()
without any parameters. What does this mean, and is it vital to my program?
| argv and argc are how command line arguments are passed to main() in C and C++.
argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.
The variables are named argc (argument co... |
3,024,314 | 3,024,441 | Boost Binary Serialization Problem | I have a problem using boost serialization using binary archives. It works when using a file stream but I want to store it in my local variable and ultimately save/load it to/from berkeley db.
When executing the program I get a boost::archive::archive_exception: 'stream error' when instantiating the binary_iarchive.
#... | Well, for one thing .data() doesn't have a terminal \0. It's not a c-string. I didn't even realize stringstream had a char* constructor (who in their right mind uses them anymore?) but apparently it does and I'd bet it expects \0.
Why are you trying to do it that way anyway? You're much better off working in C++ str... |
3,024,691 | 3,024,713 | Confusion about pointers and their memory addresses | alright, im looking at a code here and the idea is difficult to understand.
#include <iostream>
using namespace std;
class Point
{
public :
int X,Y;
Point() : X(0), Y(0) {}
};
void MoveUp (Point * p)
{
p -> Y += 5;
}
int main()
{
Point point;
MoveUp(&point);
cout << point.X << point.Y;
re... | p was declared.
void MoveUp (Point * p)
{
p -> Y += 5;
}
is a function that will take a pointer to a Point and add 5 to its Y value. It's no different to the following:
void f(int n) {
printf ("%d\n", n);
}
:
int x = 7;
f(x);
You wouldn't say n wasn't defined in that case. It's the same for p in your case.
Pe... |
3,024,724 | 3,024,742 | C++ Preprocessor Decisions | Sorry I know this is basic, but perhaps it doesn't exist or I'm not googling the right words.
Is there and an if not (is that ifndef?) an AND and an OR so I could do something like:
if not DEBUG and MACOS
| I think something like #if !defined(DEBUG) && defined(MACOS) should do it.
|
3,025,168 | 3,025,335 | Options for open source front end for C++ | I am looking for options for an open source C++ compiler front-end (source parser/analyzer) that I could customize for my requirements. I do not need the back end implementation, just that it would help to find a fast and relatively bug free C++ front end that supports most standard features. Any suggestions?
[I did g... | Clang and GCC are the two main options. GCC is very complicated (or so I've heard), and Clang is very promising but is immature.
GCC-XML uses GCC's frontend to spit out an XML description of the source. GCC-XML's output is not a full abstract source tree (it doesn't contain function bodies), but it would be a lot eas... |
3,025,293 | 3,025,845 | parser with scopes and conditionals | I'm writing a C/C++/... build system (I understand this is madness ;)), and I'm having trouble designing my parser.
My "recipes" look like this:
global
{
SOURCE_DIRS src
HEADER_DIRS include
SOURCES bitwise.c \
framing.c
HEADERS \
ogg/os_types.h \
ogg/ogg.h
}
lib stati... | I would suggest (and this is more or less right out of the compiler textbooks) that you approach the problem in phases. This breaks things down so that the problem is much more manageable in each phase.
Focus first on the lexer phase. Your lexing phase should take the raw text and give you a sequence of tokens, such as... |
3,025,373 | 3,025,683 | Scalability of Boost.Asio | I'm curious how far others have pushed Boost.Asio in terms of scalability. I am writing an application that may use close to 1000 socket objects, a handful of acceptor objects, and many thousand timer objects. I've configured it such that there's a thread pool invoking io_service::run and use strands in the appropriat... | We are using 1.39 on several Linux flavors for timers, network (both TCP and UDP), serial (20+ lines, two of which run at 500 kbps), and inotify events, and while we don't have many socket connections, we do have a few hundred async timers at any time. They are in production and they work well, for us. If I were you, I... |
3,025,450 | 3,025,476 | how to convert char * to uchar16 in JNI C++ | here's what I am trying to do:
typedef uint16_t uchar16_t;
uchar16_t buf[32];
// buf will contain timezone information like GMT-6, Eastern Daylight Time, etc
char * str = "Test";
for (int i = 0; i <= strlen(str); i++)
buf[i] = str[i];
I guess that's not correct since uchar16_t would contain 2 bytes and str co... | Strlen? buf[32]? Trying to destroy the universe?
You want to use a wstringstream.
std::wstringstream lols;
lols << "Test";
std::wstring cakes;
lols >> cakes;
Edit@Comment:
You shouldn't use strlen because any decent string system allows embedded zeros, and strlen is seriously slow. In addition, you didn't resize your ... |
3,025,807 | 3,025,815 | What are these c++ statements doing | void useproxynum ( ) { bUseProxy = true; return; };
void useacctnum ( ) { bUseProxy = false; return; };
Can anyone give me some insight into what these c++ statements are doing? There are in a header file.
bUseProxy is defined above
bool bUseProxy;
I'm trying to figure out what useproxynum is (method call?... | They are inline method definitions. The return statements are extremely unnecessary.
If it were me, i'd replace that with this:
void useNum(bool proxy) { bUseProxy = proxy; }
|
3,025,851 | 3,026,257 | C++ template function specialization using TCHAR on Visual Studio 2005 | I'm writing a logging class that uses a templatized operator<< function. I'm specializing the template function on wide-character string so that I can do some wide-to-narrow translation before writing the log message. I can't get TCHAR to work properly - it doesn't use the specialization. Ideas?
Here's the pertinent co... | A-HA!
So, I broke the problem down into it's smallest part and discovered something about the order in which template functions are matched. First, I broke the program down into this:
// main.cpp
int main()
{
Log log;
wchar_t* test = L"test";
log << test;
return 0;
}
And
// Log.h
class Log
{
public:
templ... |
3,025,920 | 3,026,338 | DWMEnableBlurBehind makes my interface controls semi transparent | I have enabled blur on my window. I have some edit fields and some custom controls and I would not want these to be affected by the blur, they are semi transparent as a result. How could I only blur the main window itself, not its child controls (sort of like Chrome). Thanks
| Black is treated as transparent since good old GDI does not support alpha channel (the alpha byte in ARGB is always 0) I'm thinking you have to do some sort of owner draw.
|
3,025,997 | 3,026,054 | Defining static const integer members in class definition | My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.
Why, then, does the following code give me a linker error?
#include <algorithm>
#include <iostream>
class test
{
public:
static const int N = 10;
};
int main()
{
std::cout << test::N << "\n";... |
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.
You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.
Interestingly, if I comment out the call to std::min, the code c... |
3,026,188 | 3,061,700 | How to get rid of void-pointers | I inherited a big application that was originally written in C (but in the mean time a lot of C++ was also added to it). Because of historical reasons, the application contains a lot of void-pointers. Before you start to choke, let me explain why this was done.
The application contains many different data structures,... | Apparently, there is no automated way/trick to convert or find all uses of void-pointers. I'll have to use manual labor to find all void-pointers, in combination with PC-Lint that will give errors whenever there is an incorrect conversion.
Case closed.
|
3,026,253 | 3,026,344 | Finding Local IP via Socket Creation / getsockname | I need to get the IP address of a system within C++. I followed the logic and advice of another comment on here and created a socket and then utilized getsockname to determine the IP address which the socket is bound to.
However, this doesn't appear to work (code below). I'm receiving an invalid IP address (58.etc) whe... | Your code already contains the hint: failed to bind socket. But you cut the part of the code that attempts connecting out (did you copy from Stevens UnP?). The socket is not connected to anything, so the network stack has not assigned the local address to it yet.
Once you connect the socket the kernel has to select th... |
3,026,263 | 3,026,333 | How to generate all variations with repetitions of a string? | I want to generate all variations with repetitions of a string in C++ and I'd highly prefer a non-recursive algorithm. I've come up with a recursive algorithm in the past but due to the complexity (r^n) I'd like to see an iterative approach.
I'm quite surprised that I wasn't able to find a solution to this problem anyw... | You could think of it as counting, in a radix equal to the number of characters in the alphabet (taking special care of multiple equal characters in the alphabet if that's a possible input). The aaaa aaab aaba ... example for instance, is actually the binary representation of the numbers 0-15.
Just do a search on radix... |
3,026,270 | 3,026,399 | Using windows CopyFile function to copy all files with certain name format | Hello! I am updating some C code that copys files with a certain name. basically, I have a directory with a bunch of files named like so:
AAAAA.1.XYZ
AAAAA.2.ZYX
AAAAA.3.YZX
BBBBB.1.XYZ
BBBBB.2.ZYX
Now, In the old code, they just used a call to ShellExecute and used xcopy.exe. to get all the files starting with AAAAA,... | You could also use SHFileOperation or IFileOperation (the latter being only available from Vista upwards but is now the recommended way according to MSDN). SHFileOperation supports wildcards and displays a progress by default, but there's also a flag for silent operation.
Check out the following MSDN links for more inf... |
3,026,300 | 3,026,331 | OpenGL: How to clear only a part of the screen? | Is it possible to not clear entire screen when using glClear() function? I need to clear only a part of the screen to save some rendering time, otherwise i would have to redraw half of the screen every frame, even if nothing is happening on the other half.
Of course this should be done as quickly (or quickier) as the g... | You might want to look into glScissor. From the documentation:
While scissor test is enabled, only pixels that lie within the scissor box can be modified by drawing commands.
|
3,026,542 | 3,026,549 | C++: Syntax error C2061: Unexpected identifier | What's wrong with this line of code?
bar foo(vector ftw);
It produces
error C2061: syntax error: identifier 'vector'
| try std::vector instead. Also, make sure you
#include <vector>
|
3,026,557 | 3,026,567 | Function to get X, Y position of an object orbiting a point, given a distance and angle in radians? | I am trying to code a function for a camera that orbits a point. Assume a 3d coordinate plane where Z is up. Ignore Z.
Let's say the camera's position starts at (0, 0, z). The object to orbit is at, say (50, 50, z). So we have a distance of ~70 units. Calling the function with {(50, 50, z), 70, x} where x is the positi... | return position + Point(distance*cos(angle), distance*sin(angle))
|
3,026,649 | 3,026,719 | Getting information about where c++ exceptions are thrown inside of catch block? | I've got a c++ app that wraps large parts of code in try blocks. When I catch exceptions I can return the user to a stable state, which is nice. But I'm not longer receiving crash dumps. I'd really like to figure out where in the code the exception is taking place, so I can log it and fix it.
Being able to get a d... | This is possible with using SEH (structured exception handling). The point is that MSVC implements C++ exceptions via SEH. On the other hand the pure SEH is much more powerful and flexible.
That's what you should do. Instead of using pure C++ try/catch blocks like this:
try
{
DoSomething();
} catch(MyExc& exc)
{
... |
3,026,666 | 3,029,006 | Display List with GLTesselated objects? (OpenGL) | Is it possible to create a display list for Tesselated objects? If so would it be more efficient?
Thanks
| Yes -- after tessellation you just have a bunch of triangles, which you can put in a display list about like anything else. Efficiency will depend; on nVidia display lists work quite well, but on ATI a display list is little different from multiple calls to glVertex.
If you want to assure efficiency across both, consid... |
3,026,682 | 3,026,781 | How to pass a function to a function? | Suppose I have a class with 2 static functions:
class CommandHandler
{
public:
static void command_one(Item);
static void command_two(Item);
};
I have a DRY problem where I have 2 functions that have the exact same code for every single line, except for the function that it calls:
void CommandOne_User()
{
// som... | Besides the C way (passing a function pointer) or the C++ way mentioned by Jay here there is the other (modern) c++ way with boost or with a compiler with c++0x support:
void Refactored_CommandUser( boost::function<void (Item)> f ) {
// alternatively std::function with proper compiler support
}
With the advantage t... |
3,026,767 | 3,026,768 | What's the difference between void* and void**? | It's the special property that void* can also be assigned a pointer to a pointer and cast back and the original value is received.
I read this line somewhere. Does it means void* and void** are same?
What is the difference?
Edit
void* can hold any pointer. Then what's void** needed for?
| One points at a black hole.
The other points at the thing pointing at the black hole.
They're not really the same thing, but pointers can be converted to void *. You can convert int * to a void * because, well, it's a pointer. void ** is still a pointer (it just points to a pointer), and since it's a pointer, you can ... |
3,026,826 | 3,027,742 | passing unicode string from C# exe to C++ DLL | Using this function in my C# exe, I try to pass a Unicode string to my C++ DLL:
[DllImport("Test.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int xSetTestString(StringBuilder xmlSettings);
This is the function on the C++ DLL side:
__declspec(dllexport) i... | Just change your export in native DLL to:
extern "C" __declspec(dllexport) int xSetTestString(wchar_t* pSettingsXML);
This will do the trick.
BTW - You cant simply do char* str1 = (wchar_t*)pSettingsXML; because it does not convert the string. You need to use wcstombs_s to convert from wchar_t* to char*. But in your c... |
3,026,858 | 3,026,874 | Segfault (possibly due to casting) | I don't normally go to stackoverflow for sigsegv errors, but I have done all I can with my debugger at the moment.
The segmentation fault error is thrown following the completion of the function. Any ideas what I'm overlooking? I suspect that it is due to the casting of the sockaddr to the sockaddr_in, but I am unable ... | It doesn't look like you ever initialize the pointer sa to point at a valid sockaddr (or sockaddr_in) object.
If you replace
sockaddr* sa;
with
sockaddr addr;
and replace all uses of sa with &addr you should be in better shape.
The same is also true of sl. At least according to the documentation for my getsockname th... |
3,026,986 | 3,027,030 | C++ namespace alias and forward declaration | I am using a C++ third party library that places all of its classes in a versioned namespace, let's call it tplib_v44. They also define a generic namespace alias:
namespace tplib = tplib_v44;
If a forward-declare a member of the library in my own .h file using the generic namespace...
namespace tplib { class SomeClass... | It looks like there is an ugly workaround for this, but no good solution.
For ACE (with a decent explanation) and Xerces (with a snarky "this is how c++ works" comment), they define macros that you can use to do this "generically".
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
class ACE_Reactor;
ACE_END_VERSIONED_NAMESPACE_DECL
... |
3,027,002 | 3,027,020 | Clipping users cursor around the X button | This should be simple, and I was hoping to do it in Delphi.
The purpose of this is just supposed to be a joke.
On a windows form application I don't want the user to be able to click the X button on the main form. I want the cursor to either clip around the X button or just set it's position elsewhere.
| Write
type
TForm1 = class(TForm)
private
{ Private declarations }
procedure NcMouseMove(var Message: TWMNCMouseMove); message WM_NCMOUSEMOVE;
public
{ Public declarations }
end;
procedure TForm1.NcMouseMove(var Message: TWMNCMouseMove);
begin
inherited;
with Message do
if HitTest = HTCLOSE ... |
3,027,067 | 3,027,533 | Optional Member Objects | Okay, so you have a load of methods sprinkled around your system's main class. So you do the right thing and refactor by creating a new class and perform move method(s) into a new class. The new class has a single responsibility and all is right with the world again:
class Feature
{
public:
Feature(){};
void... | If a feature is missing and the correct thing to do is ignore that fact and do nothing, you can get rid of your checks by using the Null Object pattern:
class MainThing {
IFeature _feature;
void DoStuff() {
_feature.Method1();
_feature.Method2();
}
interface IFeature {
void Method1();
... |
3,027,368 | 3,027,431 | Sound Manager Classes for Windows | I need some classes for playing short wav sounds, this classes would load this wav files into memory when an instance created, play sounds in background when needed, release this wav files from memory when an instance disposed.
How can I do this on C# for windows (.Net 2.0)? (Win API's sndPlaySound, OpenAL or may be a... | Check out the System.Media.SoundPlayer class. http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx
System.Media.SystemSounds too. http://msdn.microsoft.com/en-us/library/system.media.systemsounds.aspx
|
3,027,695 | 3,027,825 | What is the best C++ Mail library used to read EML file / Outlook MSG file? | We have to develop an in-house mail app. Please let me know what the best CPP library used to read EML file and Outlook MSG file?
| EML is basically the same as MHT; it's a plain text format which you can parse yourself, and I believe the WebBrowser control can also display the contents of an EML/MHT.
MSG is a binary MAPI format. You can use the MAPI libraries to deal with these (Windows only). For more information on how to deal with that, see th... |
3,027,729 | 3,027,893 | I want to trace logs using a Macro multi parameter always null. problem c++ windows | I am using the following way to cout a function's time:
#define TIME_COST(message, ...)\
char szMessageBuffer[2048] = {0};\
va_list ArgList;\
va_start(ArgList, message);\
vsprintf_s(szMessageBuffer, 2048, message, ArgList);\
va_end(ArgList); \
string strMessage(szMessageBuffer);\
CQLogTimer t(strMessage);
// CQ... | The correct version is:
#define TIME_COST(message, ...)\
char szMessageBuffer[2048] = {0};\
sprintf_s(szMessageBuffer, 2048, message, __VA_ARGS__);\
string strMessage(szMessageBuffer);\
CQLogTimer t(strMessage);
__VA_ARGS__ is not va_list type, but comma-separated arguments, so you need to use sprintf_s, not vspri... |
3,027,857 | 3,027,879 | c++ push_back doesn't work as it is supposed | I have a class symbol_table that has a vector of objects of another class row_st.also I have an enter method where inserts objects of row_st with a passed name into the vector of desired symbol_table.but when I call the enter to enter objects with name :
a;b;c;Iwill get the following result: a,b,c;b,c;c.the first eleme... | As Neil Butterworth's answer suggest, the trouble is probably not with this code, but the place where you call it. Using character pointers does not make it impossible to make things work, just harder.
The problem in this case is definitely not with push_back. If you posted the method where you call this code it might ... |
3,028,043 | 3,028,111 | How to export some data into .rtf or .doc? | Say I have created a GUI (Qt) that operates with some data(text+image). How I can export that data in one of listed formates in title.
I guess it is better to export info .rtf as it is free cross-platform formt(??), isn't it?
| See question about RTF reading and writing.
|
3,028,282 | 3,030,127 | An efficient way to compute mathematical constant e | The standard representation of constant e as the sum of the infinite series is very inefficient for computation, because of many division operations. So are there any alternative ways to compute the constant efficiently?
| Since it's not possible to calculate every digit of 'e', you're going to have to pick a stopping point.
double precision: 16 decimal digits
For practical applications, "the 64-bit double precision floating point value that is as close as possible to the true value of 'e' -- approximately 16 decimal digits" is more than... |
3,028,583 | 4,197,016 | OAuth authentication for Google API with Qt | I'm trying to get authenticated for receiving and publishing Google Buzz-es from a Qt 4.6(c++) application. I'm looking for a cross-platform solution.
Could anyone provide some working solution for this purpose?
| You can also try kQOAuth which is a new Qt library for doing OAuth authentication. It will let you do the user authentication very easily too, if you like.
Supports OAuth 1.0 and HMAC-SHA1. No external dependencies.
http://www.johanpaul.com/blog/2010/10/introducing-kqoauth-easy-and-powerful-oauth-library-for-qt/
|
3,028,632 | 8,621,112 | Move from *this in an rvalue method? | In C++11, methods can be overloaded on whether or not the expression that denotes the object on which the method is called is an lvalue or an rvalue. If I return *this from a method called via an rvalue, do I need to explicitly move from *this or not?
Foo Foo::method() &&
{
return std::move(*this); // Is this mov... | The type of *this is always an lvalue:
§9.3.2 [class.this] p1
In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. [...]
§5.3.1 [expr.unary.op] p1... |
3,028,691 | 3,028,859 | Compilation error while compiling an existing code base | While building an existing code base on Mac OS using its native build setup I am getting some basic strange error while compilation phase.
Does any of you have any idea, as I have seen it's been discussed earlier as well in this forum without any good reason. I can not see any conflicting files being included.
But stil... | It looks like you're trying to use OS X 10.3 developer tools (Xcode et al) and are trying to target OS X 10.4, which is obviously not going to work. Either change your build command to remove incompatible flags, such as -mmacosx-version-min=10.4, or upgrade to a more current version of OS X + Xcode + SDKs.
|
3,028,856 | 3,059,679 | How Can I Turn On/Off Caps Lock, Scroll Lock, and Num Lock Programmatically | Is there a method to turn on/off Caps Lock, Scroll Lock and Num Lock on Windows?
Please post the code snippet in any language... but my preference is C/C++ or Java.
P.S. I'm making a Morse Code program which blinks the Scroll Lock LED.
| The Java code is...
Get the Toolkit object...
Toolkit toolkit = Toolkit.getDefaultToolkit();
To turn on Caps Lock, Scroll Lock, Num Lock...
toolkit.setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
toolkit.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK, true);
toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, true);
To tur... |
3,028,998 | 3,029,950 | Non-blocking TCP buffer issues | I think I'm in a problem. I have two TCP apps connected to each other which use winsock I/O completion ports to send/receive data (non-blocking sockets).
Everything works just fine until there's a data transfer burst. The sender starts sending incorrect/malformed data.
I allocate the buffers I'm sending on the stack, a... | Take a serious look at boost::asio. Asynchronous IO is its specialty (just as the name suggests.) It's pretty mature library by now being in Boost since 1.35. Many people use it in production for very intensive networking. There's a wealth of examples in the documentation.
One thing for sure - it take working with buff... |
3,029,031 | 3,029,061 | Connecting C++ to C# | I've been writing a program in C++ and noticed there is a library in C# that someone else wrote that I would like to link in to my code.... but I'm not sure how to do that. Can someone suggest something? Doubt this matters, but I'm using Windows 7 with MSVC2010.
Thanks in advance!
| If you're familiar with COM you could access the .NET library through COM. If the library doesn't provide COM interop out of the box you could write a wrapper around it using C# and expose that through COM.
If you're going to pull in a .NET library you should be aware that it requires a .NET runtime which may take up v... |
3,029,164 | 3,054,982 | How to encode series of images into VP8 using WebM VP8 Encoder API? (C/C++) | How to transcode RGB images into VP8 frames (Keyframe + some dependent frames)?
So I created some images how to turn tham into VP8 now?
| First, you need a codec library for VP8:
http://www.webmproject.org/code/build-prerequisites/
Using libvpx API you can then encode your RGB frames into VP8 frames.
|
3,029,412 | 3,029,415 | Unsigned negative primitives? | In C++ we can make primitives unsigned. But they are always positive. Is there also a way to make unsigned negative variables? I know the word unsigned means "without sign", so also not a minus (-) sign. But I think C++ must provide it.
| No. unsigned can only contain nonnegative numbers.
If you need a type that only represent negative numbers, you need to write a class yourself, or just interpret the value as negative in your program.
(But why do you need such a type?)
|
3,029,523 | 3,029,526 | dynamic vector-like container but whose elements save their indexes? | All the elements should have fixed position in the array after insertion until I explicitly delete them from there. Is there something like this in boost or wherever? Thanks
| Use an unordered_map<int, T> or map<int, T>.
Or, use a vector<optional<T>>, and set the slot to delete to none_t, instead of actually deleting it.
|
3,029,545 | 3,029,583 | C++ game loop example | Can someone write up a source for a program that just has a "game loop", which just keeps looping until you press Esc, and the program shows a basic image. Heres the source I have right now but I have to use SDL_Delay(2000); to keep the program alive for 2 seconds, during which the program is frozen.
#include "SDL.h"
... | Tried with something like
SDL_Event e;
while( SDL_WaitEvent(&e) )
{
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) break;
}
? You can find many tutorials and example out there; just a fast-search example.
Added note: WaitEvent "freezes" the program so you can't do anything .. you just wait; ... |
3,029,633 | 3,029,695 | How to use dirent.h correctly | I am new to C++ and I am experimenting with the dirent.h header to manipulate directory entries. The following little app compiles but pukes after you supple a directory name. Can someone give me a hint? The int quit is there to provide a while loop. I removed the loop in an attempt to isolate my problem.
thanks!
#incl... | If you are using C++, don't use char * or arrays, use std::string:
#include <string>
....
string dirname;
cout<< "Enter a directory path to open (leave blank to quit):\n";
getline( cin, dirname );
if ( dirname == "" ) {
exit(1);
}
....
pd = opendir(dirname.c_str() );
|
3,029,860 | 3,030,528 | Catch unhandled exception of invisible thread | In my C++ application i use an activeX component that runs its own thread (or several I don't know). Sometimes this components throws exceptions. I would like to catch these exceptions and do recovery instead of my entire application crashing. But since I don't have access to its source code or thread I am unsure how i... | Try setting up an exception filter with SetUnhandledExceptionFilter().
|
3,029,923 | 3,029,930 | Can this example be done with pointers instead of global variable? | This is a simplified example of the problem I have:
#include <stdio.h>
#include <stdlib.h>
void f2(int** a) {
printf("a: %i\n", **a);
}
void f1(int* a) {
f2(&a);
}
int main() {
int a = 3;
f1(&a); // prints "a: 3"
f2(???);
return 0;
}
The problem is that I would like to be able to use f2() both in main... | You need to pass a pointer to a pointer, so you need to create a pointer in main() so that you can take its address:
int main()
{
int a = 3;
int* aptr = &a;
f2(&aptr);
return 0;
}
|
3,029,962 | 3,029,966 | boost::function function pointer to parameters? | How does boost::function take a function pointer and get parameters from it? I want wrap a function pointer so that it can be validated before being called. And it would be nice to be able to call it like boost::function is with the () operator and not having to access the function pointer member.
Wrapper func;
... | You need to overload operator(). To determine the return type, arity, and parameter types of a function, you can use something like Boost.TypeTraits:
#include <boost/type_traits.hpp>
template <typename Function>
struct Wrapper
{
typedef typename boost::function_traits<Function>::arg1_type Arg1T;
typedef typen... |
3,029,964 | 3,030,007 | Is it safe to take the address of std::wstring's internal pointer? | I have an interface which is used like the following:
if (SUCCEEDED(pInterface->GetSize(&size))
{
wchar_t tmp = new wchar_t[size];
if (SUCCEEDED(pInterface->GetValue(tmp, size)))
{
std::wstring str = tmp;
// do some work which doesn't throw
}
delete[] tmp;
}
Is it safe and portable ... | As AraK points out, the string storage might not be contiguous, though this is unlikely. You could also consider using a vector:
if (SUCCEEDED(pInterface->GetSize(&size))
{
std::vector <wchar_t> vtmp( size );
if (SUCCEEDED(pInterface->GetValue( & vtmp[0], size)))
{
std::wstring str = & vtmp[0];
... |
3,030,033 | 3,030,046 | how to go through a string array and apply functions for different strings? | Ok, this may be really noobish question, but i am wishing there is something i dont know yet.
I go through a file, and check which string each line has, depending on the string value i execute a different function for it (or functions).
This is how i do it now:
Edit: I need to use variables outside the if-else-if range... | If you just want to execute different functions, you can use a map from strings to function pointers or functors like boost::function / tr1::function:
void f1() { /* ... */ }
void f2() { /* ... */ }
// ... creating the map:
typedef void (*FuncPtr)();
typedef std::map<std::string, FuncPtr> FuncMap;
FuncMap fnMap;
fnMap... |
3,030,083 | 3,030,258 | What's the C strategy to "imitate" a C++ template ? | After reading some examples on stackoverflow, and following some of the answers for my previous questions (1), I've eventually come with a "strategy" for this.
I've come to this:
1) Have a declare section in the .h file. Here I will define the data-structure, and the accesing interface. Eg.:
/**
* LIST DECLARATION. (... | Your example is only one of the many possible uses of templates - generating a generic data structure. This example doesn't need any of the inference which makes templates powerful; asking for something which lets you create generic data structures is not really the same question as asking for something equivalent to C... |
3,030,208 | 3,030,948 | Extern variable at specific address | Using C++ and GCC, can I declare an extern variable that uses a specific address in memory?
Something like
int key __attribute__((__at(0x9000)));
AFAIK this specific option only works on embedded systems. If there is such an option for use on the x86 platform, how can I use it?
| Easy option:
Define
int * const key = (int *)0x9000;
and refer to *key elsewhere (or use a reference).
Pointerless option:
All externs have specific addresses! These addresses may not be known until link time, but they must get resolved eventually. If you declare extern int key; then you must supply an address for the... |
3,030,279 | 3,030,293 | Am I doing something wrong here (references in C++)? | I've been playing around with references (I'm still having issues in this regard).
1- I would like to know if this is an acceptable code:
int & foo(int &y)
{
return y; // is this wrong?
}
int main()
{
int x = 0;
cout << foo(x) << endl;
foo(x) = 9; // is this wrong?
cout << x << endl;
r... | The first one is correct.
For the second one, there are infinite number of solutions :), but this would be mine:
Week Week::highestSalesWeek(Week aYear[52]) // return a copy of the week
{
Week max = aYear[0];
for(int i = 1; i < 52; i++)
{
if (aYear[i].getSales() > max.getSales()) max = aYear[i];
}
r... |
3,030,655 | 3,030,678 | strongly typed C++0x enumeration comparison | why aren't instances of strongly typed C++0x enumerations comparable to each other?
Update: They are comparable in gcc 4.6; I'm not sure if it worked in gcc 4.4.
| If you use strongly typed enumerations, it's like making your enum a realy type, a class. Then it follows the same rules as for classes.
Instances of different classes can't be compared to each other by default. You have to define a comparison function (or member function) to make them comparable.
Therefore making an ... |
3,030,970 | 3,031,044 | Windows program written using MFC is a C++ program? | Every C++ books that I've read says something like this:-
All C++ programs have a main() function.
main() function is the starting point for all C++ programs.
All C++ programs begin its execution from the main() function.
However, I found that Windows programs written using MFC do not have any main() function. It use... | The answer to this question is a little more complicated than yes or no. It depends largely, on how strict you make your definition of "C++ program". A Windows subsystem program built with MSVC will not generally have a main function. MFC is a C++ language framework for building Windows subsystem programs (at least in ... |
3,031,011 | 3,031,035 | Is a display list best for this? (OpenGL) | I'm rendering 2D polygons with the GLUTesselator the first time, then they are stored in a display list for subsequent use. I think VBO's might be faster, but since I can't access the stuff that the tesselator outputs, and since it uses mixes of gl_triangle, quad, strip etc, i'm not sure how I could do this, even thoug... | It's been a while since I've used the GLU tesselator, but as I recall it just adds standard triangles to your vertex list. One of the callback functions that you pass into it will be receiving the new vertices and putting them somewhere. This happens in your code, so the data isn't hidden from you.
Display lists are ... |
3,031,105 | 3,031,123 | Exclude subexpression from regex in c++ | Suppose I was trying to match the following expression using regex.h in C++, and trying to obtain the subexpressions contained:
/^((1|2)|3) (1|2)$/
Suppose it were matched against the string "3 1", the subexpressions would be:
"3 1"
"3"
"1"
If, instead it were matched against the string "2 1", the subexpressions woul... | There are two common approaches to solving this problem:
Named capturing groups: (?P<name>), so you can pull out captured groups explicitly by name.
Non-capturing groups, usually: (?: blah), such that the group doesn't become part of the resulting group list, and the rest will remain in the expected order.
It's uncl... |
3,031,198 | 3,031,518 | Is it good practice to use assert() in class mutators? | For example:
void Date::month(unsigned int inMonth) {
assert(inMonth <= 12);
_month = inMonth;
}
If this is not good practice, what is the correct way to go about this?
| You shouldn't use assert to ensure that an argument to a public member function is valid. The reason is that there's no way for clients of your class to react to a failed assertion in any meaningful way (the fact that asserts are removed from release builds does not help either).
As a rule of thumb, assert should only... |
3,031,336 | 3,031,339 | error C2440: '=' : cannot convert from 'std::string []' to 'std::string []' | now what is wrong with this code!
Header:
#pragma once
#include <string>
using namespace std;
class Menu
{
public:
Menu(string []);
~Menu(void);
};
Implementation:
#include "Menu.h"
string _choices[];
Menu::Menu(string items[])
{
_choices = items;
}
Menu::~Menu(void)
{
}
compiler is complaining:
erro... | Array's cannot be assigned, and your arrays have no sizes anyway. You probably just want a std::vector: std::vector<std::string>. This is a dynamic array of strings, and can be assigned just fine.
// Menu.h
#include <string>
#include <vector>
// **Never** use `using namespace` in a header,
// and rarely in a source fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.