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 |
|---|---|---|---|---|
7,654,882 | 7,654,948 | What is the difference between Type** name, and Type* name[]? | What is the difference between Type** name, and Type* name[]?
Why would someone use one over the other?
Thanks
| Well that depends, is it in a variable declaration or in a function argument? If in a variable declaration:
Type** name = &pointer_to_type;
Type* name[] = { &pointer_to_type, 0, &pointer_to_type };
The first one is a pointer to pointer to type, while the second one is an array of pointers to type of length 3.
If in a ... |
7,654,928 | 7,655,012 | Boost "is_virtual_base_of" compile error when migrating working module | I have been working with boost serialization, I developed a whole module to store classes in persistent storage, but when I try to migrate my module to other project I got some errors I have never seen and I don't found any related information on the net.
The error I get is:
In file included from support.../boost_1_44/... |
boost::is_virtual_base_of<> is used somewhere in the implementation of Boost.Serialization.
In Boost 1.44, boost::is_virtual_base_of<> used types named X and Y as implementation details.
Somewhere in your other project there is a macro named X defined, breaking the X type used in the implementation of boost::is_virtua... |
7,654,958 | 7,664,748 | How to draw text using CDC with transparent background on CBitmap? | I have the following code which sort of works provided you mask out the pink pixels however what I actually want is transparent bits like a PNG file so that I can avoid alpha blending issues and the need mask out a specific color everywhere the bitmap will be used.
CClientDC dc(pWnd);
CDC memDC;
if(!memDC.CreateCompat... | About 10 minutes after asking this I read my own comment and realized that "some windows" means it was related to the windows being passed in. Specifically the font being used from said window. Fonts with default properties were exhibiting the strange blending.
At the end of the day I determined I needed to modify the ... |
7,654,964 | 7,655,003 | How to initialize static class member used in template method? | I want a static constant, LIST_DELIMITER, defined in my class below. However, I can't figure out how to declare it with templates.
// MyClass.h
#pragma once
#include <boost/algorithm/string.hpp>
#include <vector>
class MyClass
{
public:
MyClass();
virtual ~MyClass();
template<class T>
void GetAsVecto... | You have to use the exact same declaration, including qualifiers:
const std::string MyClass::LIST_DELIMITER = ",";
^^^^^
There's no template involved in this static class member definition.
|
7,654,998 | 7,655,036 | ATL how to Convert BSTR* str to registry key.SetValue(LPCTSTR str type | It's been years since I have done C++ let alone ATL code
I have this method that needs surgical help :(
This is for a mobile app so I don't want to use CString and MFC
I need to convert the BSTR* str to the correct type LPCTSTR for use in the registry Set.Value method
STDMETHODIMP CAXSampleCtl::SendMSG(BSTR* str)
{
... | COLE2T macro is just for you, see String Conversion Classes and Macros
To convert to a BSTR, pass the existing string to the constructor of
CComBSTR. To convert from a BSTR, use COLE2[C]DestinationType[EX],
such as COLE2T.
|
7,655,126 | 7,655,202 | Iteration over every object in a class | Due to the nature of a game I am making, I need to be able to create objects at random on the fly. I need to be able to change the variables of all currently existing objects of a class 60 times a second.
I've been told that although C++ is incapable of reflection, I would be able to pass the addresses of objects to a ... | "Pass the address of an object to a vector" sounds like this
std::vector<MyObject *> objectAddresses;
This is a vector of pointers to MyObject. Note that you have to add and remove the pointers manually. Failure to remove an object's pointer from this vector when it is deleted can easily crash your program.
Depending ... |
7,655,217 | 7,655,229 | Resolving StackOverFlowException in C++ | I am trying to write a program for selection sort of the elements an array in C++ (VS2010) using recursion. The program works without any issues for for smaller arrays where the size of the array is less than 10 when I increase the size of the array to 10000 I am facing stackoverflow exception. How do I go about resolv... | Either increase the size of the stack (which can be done with the STACK linker option) or -- and this is a much better option -- improve or replace your algorithm. It sounds like a recursive algorithm may not be suitable for the kind of data you need to process, but maybe you can improve things by using fewer local var... |
7,655,294 | 7,655,414 | TThread Access Violating on Terminate/Free | I am running a short bit of code that will occasionally (very rarely) Access Violate on the Terminate/Free of my TThread. I am running many instances of these threads but this spot seems to be the only ones that is causing problems and it only does so once every 500 or so calls.
TThreadInheritor* Base= new TThreadInhe... | Never free a TThread that is still running. The base class TThread destructor is not safe in that regard. It does some pretty stupid things that can cause problems. ALWAYS make sure a TThread is fully terminated before freeing it. Use the WaitFor() method, or wait until WaitForSingleObject() reports WAIT_OBJECT_0.
|
7,655,368 | 8,470,122 | Linkage error using shared dll with minimal C++/SWIG/Lua code | This is a really specific compilation problem involving C++, SWIG and Lua.
I have a really simple base code :
[AClass.hpp]
class AClass {
public:
AClass();
};
[AClass.cpp]
#include "AClass.hpp"
AClass::AClass() {}
[main.cpp]
#include "AClass.hpp"
int main() {
AClass my_a;
}
At this point, there is no matte... | g++ under mingw might require __declspec(dllimport/export)
|
7,655,635 | 7,655,660 | How do I save user information (like NSUserDefaults in obj-c) with C++? | In objective-c it's easy. Although, in C, you have to call fopen, read, close and all of that jazz. How do you do it in C++?
| just use the header fstream
example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("file.txt");
file << "Test!\n";
file.close()
return 0;
}
|
7,655,736 | 7,655,777 | Win32: Changing Program Icon | I had originally decided that IDI_ICON1 would be a good fit for my program:
wndclass.hIcon = LoadIcon (HINST_THISCOMPONENT, MAKEINTRESOURCE(IDI_ICON1));
The icon then appeared in the top left of the title menu for my main window and for the .exe file in Windows explorer.
I decided I liked IDI_ICON2 better, so ... | Explorer takes the first icon in your executable. That will be the one with the lowest id. Try managing your resources so that IDI_ICON2 is defined to be a lower integer than IDI_ICON1.
|
7,655,766 | 7,656,438 | Dynamic Stack Memory Reallocation | I'm fairly new to C++ and new to pointers as well. I'm currently working on a stack and was trying to reallocate the memory for the stack as the size of the stack reaches the top however, I'm running into issues. I've already done a lot of research both on Google and stack overflow and have found some information helpf... | The problem is that you don't want to reallocate the top of the stack. Rather, you want to allocate a new array of values which is large enough to hold the new values. Also, since you need to reallocate the array, values should be a pointer.
But how about we forget all this. If we're working in c++, let's use what c++ ... |
7,656,055 | 7,665,923 | How do I prepare my .cpp files for the Android ndk to build them? | We currently have some image processing software written in c++ which is being used by our IOS application. I am trying to integrate this image processing code into the android project that I created using the Android NDK.
I have my android project and the sdk all setup and ready to go. I also have the ndk setup and re... | 1) You should be able to build without alteration, but you will need to write some of those JNI wrapper functions to call it from Java. Hopefully you have a small number of top-level classes and you will only need to wrap those. E.g. Here's what I have for a game I'm (slowly) writing:
// android.cpp
#include "game.h"
#... |
7,656,104 | 7,656,211 | Can I guarantee the C++ compiler will not reorder my calculations? | I'm currently reading through the excellent Library for Double-Double and Quad-Double Arithmetic paper, and in the first few lines I notice they perform a sum in the following way:
std::pair<double, double> TwoSum(double a, double b)
{
double s = a + b;
double v = s - a;
double e = (a - (s - v)) + (b - v);
... | Yes, that is safe (at least in this case). You only use two "operators" there, the primary expression (something) and the binary something +/- something (additive).
Section 1.9 Program execution (of C++0x N3092) states:
Operators can be regrouped according to the usual mathematical rules only where the operators reall... |
7,656,219 | 7,656,260 | C/C++ function for generating a hash for passwords (using MD5 or another algorithm)? | I'm looking for a function for C/C++ that behaves identically to PHP's md5() function -- pass in a string, return a one-way hash of that string. I'm also open to other algorithms than md5() if they are as secure (or more secure), reasonably fast, and ideally one-way.
The reason I'm searching for said function is for t... | Seriously, use a library (OpenSSL is a good choice). They're well-tested, and you can just drop them into your project without having to worry if you get the code right or not. Don't worry about the size of the library, any functions you don't use will not be included in your final executable.
I'd also recommend avoi... |
7,656,292 | 7,656,625 | Adding functions erf() and erfc() to math.h _ basics of C . | I am working with the Borland Turbo C++ compiler in a WINDOWS machine, and wrote a piece of code in C.
I want to use the complementary error function erfc() for one of my calculations.
However, when I run the code, the error is
"Linker error: Undefined symbol _erfc in in module filename.c "
The problem here is erfc(... | It's likely that you need to pass some special option to link to the math library.
It's also possible that Borland Turbo C++ doesn't support the erfc() function.
In C, the 1990 ISO C standard didn't include the erfc() function. It was added to the language by the 1999 standard. (I'm not sure about C++.) I think that... |
7,656,521 | 7,656,536 | How to modify a C++ structure with int * | I have the following structure:
struct CountCarrier
{
int *CurrCount;
};
And this is what I want to do:
int main()
{
CountCarrier carrier = CountCarrier();
*(carrier.CurrCount) = 2; // initialize the *(carrier.CurrCount) to 2
IncreaseCount(&carrier); // should increase the *(carrier.CurrCount) to 3
... | struct CountCarrier
{
int *CurrCount; //No memory assigned
};
You need to allocate some valid memory to the pointer inside the structure to be able to put data in this.
Unless you do so, What you ar trying to do is attempting to write at some invalid address, which results in an Undefined B... |
7,656,565 | 7,656,660 | Default Constructors all encapsulated in the header files | While in my class today, we had an exercise in inheritance. We were to write a UnderGrad class that inherited from a Student class which inherited from a Person class.
The Person had 3 variables to the class a name, an address and a birthday.
The Student had an ID number, Major and degree type.
And finally the Undergra... | Without the benefit of the context of the code, there are only a few things that I would change about these constructors.
I would consider moving the definitions of the constructors into separate source files. This will allow the definitions to be changed without triggering a recompile of the rest of your code. For sm... |
7,656,599 | 7,656,833 | building a shell - IO trouble | I am working on a shell for a systems programming class. I have been having some trouble with the file redirection. I just got redirecting the output to work, e.x. "ls > a" however when I type a command like "cat < a" into my shell it deletes everything in the file. I feel like the problem stems from the second if stat... | Your call open(_inputFile, 0777) is incorrect. The second argument to open is supposed to contain a bitwise or'd combination of values that specify access mode and file creation flags, among other things (O_RDONLY, O_WRONLY, etc). Since you're passing 0777, that probably ends up containing both O_CREAT and O_TRUNC, whi... |
7,656,633 | 7,656,964 | Pattern for realizing low priority background threads? | I have a (soft) realtime system which queries some sensor data, does some processing and then waits for the next set of sensor data. The sensor data are read in a receiver thread and put into a queue, so the main thread is "sleeping" (by means of a mutex) until the new data has arrived.
There are other tasks like loggi... | Your problem is with OS scheduler, not the C++. You need to have a real real-time scheduler that will block lower priority threads while the higher priority thread is running.
Most "standard" PC schedulers are not real-time. There's an RT scheduler for Linux - use it. Start with reading about SCHED_RR and SCHED_FIFO, a... |
7,656,688 | 7,656,787 | Member function declared, but compiler says its not | This is my Position.h file:
#ifndef POSITION_H_
#define POSITION_H_
class Position{
public:
Position(int v);
int pos();
private:
int value;
bool win;
};
#endif
This is my Position.cpp file:
#include "Position.h"
Position::Position(int v):value(v){
}
int Position::pos(){
return value;
}... | Its compiling for me... you must be doing something weird.
|
7,656,962 | 7,657,230 | C++ override function of object created by subclass | I was wondering if it's possible to override just one function in a class without creating an entirely new class.
I would like bObj1.foo(); to output "foo!" and bObj2.foo() to output "foo?", but currently they both output "foo!".
#include <iostream>
using namespace std;
class B {
public:
virtual void foo() { c... | You can get the behavior that you want with a simple change, which consists in moving the "virtual" behavior to the A and C classes.
Here I modified your application to return the expected result:
#include <iostream>
using namespace std;
class A;
class B {
public:
B(A& a) : aref(a) {}
void foo();
private:
... |
7,657,051 | 7,657,351 | Difference between static method and non static function in memory | As I understand, each instance of a class has its own member variables in memory, so that it can store different values for different objects. However, it is not the same for member functions. Member functions are reused across objects of a class, so it only has one address with one block of memory to refer when needed... | This differs from language to language, but in C or C++03 functions generally map on assembly functions; that is they exist once in memory (whether free functions, class functions or class static functions) and take arguments as parameters, including a this pointer for member functions that is implicit.
In C++11, lambd... |
7,657,229 | 7,657,251 | What might cause our application not work? C++ | void CCaptureDlg::ListDevice()
{
((CComboBox *)GetDlgItem(IDC_COMBO_DEVICE))->ResetContent();
HRESULT hr;
IMoniker * pMoniker =NULL;
ULONG cFetched;
ICreateDevEnum * pDevEnum =NULL;
hr = CoCreateInstance (CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
IID_ICreateDevEnum, (void ** ) &pDevE... | I can only think of a buggy video capture device which shows this error message, or another part of your code which you did not provide. There is nothing here in this code snippet to do such a prompt.
If you have a weird message box coming out of nowhere, the debugging you can do is to break with debugger without closi... |
7,657,419 | 7,657,550 | How to reduce the crash of the C++ program | I have a big software implemented by C++, built by VC10 SP1. There are more than 15 millions of source code lines. It is delivered to Windows platform, both win32 and x64. From the crash reports, the mean time to crash is only about 40 minutes.
I want to try the best to reduce the crash and extend the mean time to cras... | This is called debugging, or the Art of Hunting Bugs.
There are many ways to improve Software Quality.
During the Design Phase:
Design Reviews
Code Reviews
Static Analysis Tools
During the Early Life:
Unit Testing
Fuzzy Testing (where applicable)
Integration Testing
End-to-End Testing
The whole lot can be run on in... |
7,657,575 | 7,657,642 | Tail recursion optimization in C++ code | I wanted to see the impact of tail recursion optimization and want to write simple factorial function in a tail recursion optimized way.
Is it possible to do this in the code without compiler supporting it?
| The compiler does the optimization. So it is not possible to test it without compiler support.
The only way to do this in code is to replace the recursion by iteration (but then of course you lose the recursion).
|
7,657,682 | 7,657,880 | Passing temporaries as non-const references in C++ | I have the following piece of code, as an example dec_proxy attempts to reverse the effects of the increment operator upon the type that is executed in a complex function call foo - which btw I cannot change the interface of.
#include <iostream>
template<typename T>
class dec_proxy
{
public:
dec_proxy(T& t)
:t_... | Taking Stephen's advice, you should look at the answer to How come a non-const reference cannot bind to a temporary object? and simply add a member function that returns a reference dec_proxy, e.g.:
dec_proxy &ref() { return *this; }
and call foo:
foo(
dec_proxy<int>(i).ref(),
dec_proxy<double>(j).ref(),
... |
7,657,718 | 7,658,089 | When to use shared_ptr and when to use raw pointers? | class B;
class A
{
public:
A ()
: m_b(new B())
{
}
shared_ptr<B> GimmeB ()
{
return m_b;
}
private:
shared_ptr<B> m_b;
};
Let's say B is a class that semantically should not exist outside of the lifetime of A, i.e., it makes absolutely no sense for B to exist by itself. S... | Your analysis is quite correct, I think. In this situation, I also would return a bare B*, or even a [const] B& if the object is guaranteed to never be null.
Having had some time to peruse smart pointers, I arrived at some guidelines which tell me what to do in many cases:
If you return an object whose lifetime is to ... |
7,657,910 | 7,657,925 | array's initialization body as function parameter (C-array), is it possible? | I am searching for some help in next situation:
I have some class and some method in it, syntax is like this:
class SomeClass {
public:
void doSomething(int *a);
};
So I want to call this method like
SomeClass::doSomething({ 0, 1, 2, 3, 4 });
Is it possible in any language?
Any (C++, C, obj-... | This is about C++11 initializer lists (section 18.9).
void foo (std :: initializer_list <int> inputs) {
for (auto i : inputs) {
// ...
}
}
foo ({10, 20, 30});
Only the compiler can create an initializer list, but you can treat it like a standard STL-style container with begin(), end(), size(), and ran... |
7,657,916 | 7,658,070 | Assigned objects in child function not updated in parent function | This is a cgal related question, but I think it is also a general C++ question, so I ask it here.
I am trying to use the Alpha_shape_2 class, and assign it to AlphaShapeCg class in a subroutine named GetAlphaShalCg. The problem is that some of the function in Alpha_shape_2 doesn't return correct result.
This is my cod... | You're assigning a pointer to a local variable that gets destroyed when you exit the function.
If you want to create the object in the function and return its address - you should use dynamic allocation (new it, don't forget to delete when you're done with it).
|
7,658,090 | 7,658,132 | Printing as a 1 d array rather than 2 -dimensional array | Can anyone tell me why this is printing as a 1-d array rather than a 2 -d? Nevermind im an idiot.
int colls = 5;
int rows = 4;
int array[rows][colls];
for (int x=0; x < rows; x++)
{
for (int g=0; g < colls; g++)
{
array[x][g]=0;
cout <<array[x][g];
}
}
| Firstly your array dimensions must be "const". Secondly you need a endline at the end of the inner loop.
|
7,658,219 | 7,658,312 | Bad Access Error in 2D-Array (Matricies) | I have a little bit of a problem... I understand what a EXC_BAD_ACCESS error is and I generally know how to fix it but this one has got me completely stuffed. I have this all within a class, here is one method:
double Matrix::get_element(int r, int c) const {
//Retrieve the element at row r and column c
//Shoul... | It is impossible for us to say when you do not state how you declare and initialize the matrix element. Using something like that in your CTOR should be fine:
class Matrix {
float matrix[3][3];
...
}
Don't forget to initialize it in your CTOR to something that makes sense.
Btw: why do you do this: Matrix working... |
7,658,487 | 7,658,598 | The use of declaring function inside a function? |
Possible Duplicate:
Is there a use for function declarations inside functions?
I know that inside function we can declare a function. What is the use of it? Can you please bring a simple example?
| There is little value to declaring a function inside a function, unless you intend on defining it later and only having it available to that function- i.e., the function declaration is encapsulated.
int main() {
void foo();
foo();
}
void some_other_func() {
foo(); // ERROR
}
void foo() {
}
But that's it. I... |
7,658,609 | 7,673,603 | including class-files dynamically | Right now I´m working on porting Fitnesse´s Slim-Server from java to Qt, which requires me to be able to load classes that don´t exist yet.
I already found out how to instantiate the yet unknown class here:
How I can get QMetaObject from just class name?
But for this I need the class.h file already included, right?
So ... | I finally came up with a solution, which - after some hours of trouble - is now working.
The QLibrary class allows to load .dll-files dynamically, so all I had to do was putting my class into a .dll, and add a function, that returns a pointer to the required class.
this is the .dll´s header-file:
#ifndef DIVFIXTURE_H
#... |
7,658,925 | 7,658,945 | Class constructor not working? | Code:
In class header file:
class Coconuts
{
public:
Coconuts constructor();
};
In class .cpp file:
#include "Coconuts.h"
#include <iostream>
#include <string>
using namespace std;
Coconuts::constructor()
{
cout << "\nYay coconuts are initialized";
};
In main():
Coconuts Object1;
My ... | Constructors are not functions named constructor. The "name" of a constructor is the name of the class itself. Note that constructors are not normal functions and cannot be directly referenced by name, which is why I put "name" in quotation marks.
Your code should be as follows:
//.h
class Coconuts
{
public:
Coconu... |
7,659,103 | 7,659,209 | How to use policy-templates if the types of two templates are linked? | I'm currently writing a class which allows getting and setting interal program options and it should be quite flexible and easy to use.
Specifically, an option is identified by an enum type and a value type, which have a one-on-one relationship. For example, an enum IntType will contains options which have an int type.... | It is not necessary to pass both the Enum and the type. You can deduce the enum value from the type itself thanks to a traits class:
template <typename T>
struct PolicyTraits;
template <>
struct PolicyTraits<int> { static Enum const value = IntType; }
// ... and so on ...
Your selection is obviously a bit more diffi... |
7,659,127 | 9,115,771 | CreateEx Causes Unhandled exception The activation context being deactivated is not the most recently activated one | itsAnalysisDataTable.CreateEx( WS_EX_CLIENTEDGE, AfxRegisterWndClass( CS_DBLCLKS, LoadCursor( NULL, IDC_ARROW ), (HBRUSH)::GetStockObject( NULL_BRUSH ), NULL ), "AnalysiysTable", WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_TABSTOP, dialogItemRect, this, IDC_ANALYSIS_DATA_TABLE );
This line has cost me two days of effort w... | After hitting a lot of these, I've found the simple way to track down the root issue is to go to Debug -> Exceptions and enable ALL Thrown exceptions. Then you'll find there is some other exception that is firing, being silently caught, BUT messing up the activation context. Once you fix the first exception, the acti... |
7,659,322 | 7,659,467 | How to define template function within template class in *.inl file | I write template declaration in *.hpp file and their "definition" in *.inl file linked from *.hpp
just like this:
//*.hpp
template <typename T1, typename T2>
class SomeClass
{
public:
void someMethod();
};
//*.inl
template <typename T1, typename T2>
void SomeClass<T1, T2>::someMethod()
{
}
but how to write extra ... | Here's your definition:
template <typename T1, typename T2>
template <typename E>
void SomeClass<T1, T2>::extraTypedMethod(E & e)
{
}
|
7,659,386 | 7,663,797 | can i add external dll to npapi plugin , that suppos to be installed in the browser? | Im building plugin to FF and Chrome , this plugin needs to call API methods that are in external dll/so . can i bundle that npapi plugin with external dll in the plug ?
| Of course you can. Keep in mind that some people seem to have trouble getting a linked DLL to load from the plugin DLL directory, so you might need to delay load it and set the DLL search path on plugin startup to search in the directory the plugin is in, but you can install the dependency along with the plugin DLL.
|
7,659,400 | 7,659,547 | How do I reference a static function to pass as a parameter? | I have a static function callback:
static SCDynamicStoreCallBack callback( [params] ){ ... }
In main, I'm calling
createIPAddressListChangeCallbackSCF(callback, manager, &storeRef, &sourceRef);
This function requires a callback function to be passed as a parameter. However when I try and compile, I get the error
err... | I think the problem is that callback() is not defined in the same file as main().
static functions (and variables) aren't visible across files, even if there's a prototype or extern declaration. So, either callback() has to move to the same file as main(), or it has to lose its static'ness.
If both functions are in the... |
7,659,447 | 7,660,295 | How To playback to memory with mplayer | I need to embed a video player into my program (C++) but I cannot use XEmbed, because I must do some postprocessing.
Is it possible to write the output as a raw RGB to a buffer of memory like you can do with ffmpeg?
| Unfortunately mplayer cannot run as a library but there might be a bit of a hacky solution if you are willing to do some changes to the mplayer code. This should also work on Windows and MacOSX but needs some adapting.
Download mplayer sources and look-up the ./libvo/vo_png.c file. You can use this file as a template a... |
7,659,539 | 7,659,750 | Qt eventFilter for CTRL+TAB shortcut is processed further even when true is returned | I'm trying to override the Ctrl+Tab behaviour of QMdiArea by installing an eventFilter on the area.
The implementation I'm using to test ignoring the event is as follow:
bool
MyEventFilterClass::eventFilter(QObject * watched, QEvent * e)
{
if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease ||
... | QMdiArea is already using an event filter to catch Ctrl+Tab, so you have to create a derived class of QMdiArea and redefine its eventFilter function.
And since there is a lot of other things in QMdiArea::eventFilter, don't forget to call it back for the events you don't want to block or handle.
|
7,659,676 | 7,659,828 | Is it possible that a set contains two shared pointer to the same object? | In my code I have two vectors:
vector<lipid*> lipids;
vector<shared_ptr<bead> > ions;
The lipid class:
class lipid{
public:
lipid();
lipid(double x, double y, bool up, int LID);
~lipid();
void makeMe(int LID);
std::tr1::shared_ptr<bead> head;
std::tr1::shared_ptr<bead> body;
std::tr1::shared_ptr<bead> t... | No, it isn't possible.
std::set guarantees that it containes no duplicates. Whether an instance is a duplicate of another is decided by applying the second template argument, which defaults to std::less.
The standard library provides an operator < that operates on std::shared_ptr, performing a less than comparrison on ... |
7,659,846 | 7,659,907 | Endian-ness in a char array containing binary characters | I'm building some code to read a RIFF wav file and I've bumped into something odd.
The first 4 bytes of the file header are the word RIFF in big-endian ascii coding:
0x5249 0x4646
I read this first element using:
char *fileID = new char[4];
filestream.read(fileID,4);
When I write this to screen the results are as ... | You are simply on a little-endian machine, and the "RIFF" string is just a string and thus neither little- nor big-endian, but just a sequence of chars. You don't need to reverse the bytes on a little-endian machine, but you need to when operating on a big-endian.
|
7,659,938 | 7,659,987 | Syntax error: Array of Vectors in OO C++ | I've got an outline of a HashTable class I'm trying to make. I'm getting 3 errors output from Visual Studio, but I can't see the problem here. I'm fairly new to OO in C++ so it's probably something i've missed. It claims there is a problem with my array of vectors. The errors are:
error C2143: syntax error : missing... | The C++ here is valid (once you fill in the empty functions). The problem is with how Visual C++ uses precompiled headers. When you use precompiled headers (the default setting), the Visual C++ compiler expects the first line of each implementation file to be #include "stdafx.h", and doesn't compile anything that appea... |
7,659,949 | 7,660,419 | Is it possible to add a version number to a file that will be visible in Properties/Details in windows explorer | I have an unmanaged C++ project where I am writing data to a custom file format that I have defined.
What I would like to know is if there is a way to add a header that is compatible with Windows Explorer so that a version number will be displayed, as in the example below showing a Windows font.
The purpose of this i... | You cannot achieve this for a file in general. But if your file format stores a version information, you can teach the Windows Explorer to display it.
You have to write a Shell Extension for the Explorer, that can extract arbitrary information out of your files. This extension must be installed on the target computer ... |
7,660,035 | 7,660,063 | Not able to call a public method on pointer stored in a container | Strangely I am getting compilation error in C++ for the following code.
class A
{
public:
void sayHai()
{
cout << "\n Hai";
}
};
int main(int argc, char** argv)
{
vector< A* > vectorA;
vectorA.push_back(new A());
for (vector< ... | Probably just be operator precedence. The error message looks like its trying to call the sayHai method of the iterator. So do this instead:
(*iter)->sayHai();
|
7,660,100 | 7,660,326 | What is happening here in this C++ code? | Can anyone please explain what is going in this C++ code. It compiles and executes fine on Linux.
#include <iostream>
using namespace std;
int main = ( cout << "Hello world!\n", 195 );
| The number "195" is the code of RET instruction on x86.
The C++ compiler (gcc in my case) is unable to recognize that "main" wasn't declared as a function. The compiler only sees that there is the "main" symbol, and presumes that it refers to a function.
The C++ code
int main = ( cout << "Hello world!\n", 195 );
is in... |
7,660,195 | 11,303,487 | Can I use CFPropertyListWriteToStream with stderr? | I want to use CFPropertyListWriteToStream to write to stderr. If I put in stderr as an argument, I get the error:
error: cannot convert ‘FILE*’ to ‘__CFWriteStream*’ for argument ‘2’ to ‘CFIndex CFPropertyListWriteToStream
How can I make a CFWriteStream object that writes to stderr?
| You could use the technique I found here:
CFWriteStreamRef stdoutStream = NULL;
if (verbose) {
CFURLRef devStdout =
CFURLCreateWithFileSystemPath(NULL, CFSTR("/dev/stderr"),
kCFURLPOSIXPathStyle, false);
stdoutStream = CFWriteStreamCreateWithFile(NULL, devStdout);
if (stdoutStr... |
7,660,348 | 7,660,436 | Injecting types from nested namespaces: Typedef or using? | I have a large software framework which is currently living in a common namespace. Recently, I've moved some classes into nested namespaces, but in order to preserve backwards compatibility for the time being, I need to keep the names in the global namespace. So far, I'm using using:
namespace framework {
namespace I... | They're somewhat different things: The typedef introduces a new type name framework::IStream, whereas the using directive only affects the name lookup inside the scope in which it appears. (This has additional effects if you were to also define a separate, genuine type framework::IStream, but since you're not doing tha... |
7,660,474 | 7,660,652 | Got so many error when compiled C++ in Xcode | everyone
I try to add c++ class into my iphone project.but I got so many error message
for example , in MyClass.h
struct DefaultData{
char id[32];
char name[256];
};
struct DefaultDataList{
int size;
//Here got a error1 : **Expected specifier-qualifier-list before "DefaultData"**
DefaultData *dat... | Objective-C does not support C++ classes - you need Objective-C++ to mix C++ with Objective-C.
As for your errors, the code you've posted is neither valid C nor C++.
|
7,660,494 | 7,660,585 | How best can I programmatically apply `__attribute__ ((unused))` to these auto-generated objects? | In my makefile I have the following target, which "compiles" text/HTML resources into unsigned char arrays using xxd -i.
I wrap the result in an anonymous namespace and header guards for multiple-inclusion safety both inside and between translation units.
templates.h:
@echo "#ifndef TEMPLATES_H" > templates.h
@... | I think a quick sed should work, given that the output of xxd -i is very regular:
xxd -i $$i | sed -e 's/ =/ __attribute__((unused)) =/' >> ../templates.h
|
7,661,114 | 7,664,755 | the OpenMP "master" pragma must not be enclosed by the "parallel for" pragma | Why won't the intel compiler let me specify that some actions in an openmp parallel for block should be executed by the master thread only?
And how can I do what I'm trying to achieve without this kind of functionality?
What I'm trying to do is update a progress bar through a callback in a parallel for:
long num_item... | #include <omp.h>
void f(){}
int main()
{
#pragma omp parallel for schedule (guided)
for (int i = 0; i < 100; ++i)
{
#pragma omp master
f();
}
return 0;
}
Compiler Error C3034
OpenMP 'master' directive cannot be directly nested within 'parallel for' directive
Visual Studio 2010 OpenMP 2.... |
7,661,131 | 7,661,752 | c++ thread for quadcore | Can you tell me how can I set a thread to run all of the core of my cpu? I make a thread with:
CreateThread(0, 0, Thread, (LPVOID)1, 0, 0);
but it only run at 25% speed of my cpu, because it only takes 1 core to do calculates. How can I set it to use all the 4 for full speed?
| A thread will run on a single core at any one time, though it may be switched between cores by the OS. To have your application take advantage of more than one core then you will need more than one thread.
You can use CreateThread to start these threads, or a wrapper around it such as boost::thread, or the new C++11 st... |
7,661,147 | 7,662,595 | Copy a matrix to a subset of another matrix | I'm having difficulty copying a subset of a matrix into another larger matrix using OpenCV in C++.
I tried the following code:
#include <opencv2/opencv.hpp>
void printMatrix(const cv::Mat &M, std::string matrix)
{
printf("Matrix \"%s\" is %i x %i\n", matrix.c_str(), M.rows, M.cols);
std::cout << M << std::endl... | Your code doesn't compile for me. I get an error at R0.copyTo(P0.colRange(0,2)); (and also if I try R0.copyTo(P0.colRange(0,3)); which has the correct range.) But this does work for me:
cv::Mat dest(P0.colRange(0,3));
R0.copyTo(dest);
printMatrix(P0, "P0 with R");
You almost had it in your last code exampl... |
7,661,155 | 7,661,223 | QT app compiled in under Windows performs calculation incorrectly | I have constructed my first piece of software using QT and C++, which is working perfectly when compiled on Ubuntu 11.04 and Mac OS X. When I compile on Windows, I get strange output in my GUI. I have tracked down the problem to an error calculating the paint coordinates. This is the offending calculation:
long x = ((p... | long type in Windows is 32-bit.
You should use long long -type if you want 64-bits len or qint64 when you use Qt.
|
7,661,347 | 9,341,899 | push_backing into list of pointers causes memory leak | I am trying to find memory leak with Visual Leak Detector.
It shows me m_neighbors.push_back(ent); causes leak.
(brief callstack = NeighborCalculatorDummy -> foreach -> list -> allocate)
I use it as NeighborCalculatorDummy<Entity *>, so pushback should just insert pointer in list without any allocation.
All pointers to... | I have omitted virtual destructor in Entity's parent. That is why pushbacking it caused a leak.
|
7,661,392 | 7,661,521 | Is it OK to have a throwing swap member-implementation? | The general guideline when writing classes (using the copy-and-swap idiom) is to provide a non throwing swap member function. (Effective C++, 3rd edition, Item 25 and other resources)
However, what if I cannot provide the nothrow guarantee because my class uses a 3rd party class member that doesn't provide a swap opera... |
So, is it OK to have a potentially throwing swap member function if you can't help it? (Or do you know ways around this conundrum?)
There is nothing inherently wrong with having a swap function that can potentially throw, but beware that without the strong exception guarantee in swap, it cannot possibly be used to pr... |
7,661,473 | 8,148,229 | Difference between proactor pattern and synchronous model in web server | In synchronous model, when a client connects to the server, both the client and server have to sync with each other to finish some operations.
Meanwhile, the asynchronous model allows client and server to work separated and independently. The client sends a request to establish a connection and do something. While the... | The Proactor model assumes splitting the network session process in a subtasks like: resolving hostname, accepting or connecting, reading or writing some part of information, closing connection - and allows you to switch between subtasks from different sessions. Whereas, the Reactor model sees the network session proce... |
7,661,491 | 7,669,135 | cursor won't move when using move() or wmove() when using the curses library | I have this program which prints the first 5 lines or more of a text file to a curses window and then prints some personalized input. but after printing the lines from the text file, the cursor wont' move when using move or wmove. I printed a word after using both and refresh() but it is printed in the last position t... | I suspect that you are trying to print outside the bounds of the window.
In particular, I would guess that here:
mvwprintw(results_scrn,num_rows_res,(num_col_res/2) - 2,"Close");
...num_rows_res is the number of rows in the results_scrn window - but that means that the valid row coordinates range from 0 to num_rows_re... |
7,661,643 | 7,664,332 | How to detect the first and the last argument in the variadic templates? | How to detect the first and the last argument in the variadic templates?
For the 1st argument it is easy (just compare sizeof...(T) with 0), but is there a way to detect the last element?
The example :
#include <iostream>
#include <typeinfo>
template < class... T >
struct A
{
int foo(int k){ return k; };
};
tem... | I'm not positive if this is what you want. But here are two utilities named first and last that take variadic templates and typedef the first and last type respectively:
#include <iostream>
#include <typeinfo>
template <class T1, class ...T>
struct first
{
typedef T1 type;
};
template <class T1, class ...T>
stru... |
7,661,691 | 7,661,768 | Summing bool values in C/C++ | Consider the C++ code below:
bool a = 5;
bool b = 6;
int c = (int)a + (int)b;
When I compile&run this code, c has the value 2. Does the standard guarantee that, in any compiler/platform, bool values initialized with false (0) or true (not necessarily 1) will be 1 in operations and the code above will always result in ... | Section 4.7 (integer versions) of the C++ standard says:
If the source type is bool, the value false is converted to
zero and the value true is converted to one.
Section 4.9 makes the same guarantee for floating point conversions.
|
7,662,048 | 7,662,068 | Comparing 2 wchar_t arrays | I'm sure this is sooo simple but I've come from a c# background where strings are easy and now I am making a small trip into the unmanaged world I am very confused.
Essentially I am using EnumDisplayDevices to list the available devices, I want to target a particular adapter so I need to compare DeviceString and Device... | Use a std::wstring, it has an operator==.
|
7,662,109 | 7,662,804 | Should we generally use float literals for floats instead of the simpler double literals? | In C++ (or maybe only our compilers VC8 and VC10) 3.14 is a double literal and 3.14f is a float literal.
Now I have a colleague that stated:
We should use float-literals for float calculations and double-literals for double calculations as this could have an impact on the precision of a calculation when constants are... | Yes, you should use the f suffix. Reasons include:
Performance. When you write float foo(float x) { return x*3.14; }, you force the compiler to emit code that converts x to double, then does the multiplication, then converts the result back to single. If you add the f suffix, then both conversions are eliminated. ... |
7,662,356 | 7,662,375 | Using standard exception class | I am trying to use a standard exception class in c++ like:
#include <iostream>
#include <exception>
using namespace std;
int main(){
int a[6]={12,3,2,4,5,6};
int n=6;
try{
cout<<a[6]<<" ";
}
catch(std::exception & exc)
{
cout<<exc.what();
}
return 0;
}
But in... | Accessing a[6] is undefined behaviour, since the only valid indices for a are 0..5.
You shouldn't expect a[6] to perform any bounds checking, much less throw a C++ exception on out-of-bounds array access.
If do you want automatic bounds checking, make a into std::vector<int> and use a.at(index) to access its elements.
|
7,662,411 | 7,662,508 | Storing elements in an unordered_set vs storing them in an unordered_map | Suppose I have the following User struct:
struct User {
string userId;
UserType userType; // UserType is just an enumeration
string hostName;
string ipAddress;
//and more other attributes will be added here
};
and I need to store a collection of user records (around 10^5 users, can scale highe... | I would choose unordered_map, because I can get a user, given a userid at any time, without any extra work, while with unordered_set I don't have this facility.
As for the mentioned operations, the speed will be almost same.
|
7,662,583 | 7,664,383 | Cmake multi-library scenario | We would like to organize a C++ project like this:
project/
lib1/ (first library)
CMakeList.txt
src/
lib1.c
foo1.h
build/
test/ (tests)
CMakeList.txt
test1.c
test2.c
lib2/ (second library)
CMake... | The whole philosophy is to start with a central CMakeLists.txt for your whole project. At this level all the targets (libs, executables) are gonna be aggregated so there will be no problem linking from lib1 to lib2 for example. If lib2 is gonna be linking to lib1, lib1 needs to be built first.
Platform specific source ... |
7,662,637 | 7,662,707 | Acceptable programming practice - conversion and upcasting | Is the following acceptable programming practice:
class TestA
{
protected:
int A;
public:
TestA(){A = 10;}
TestA &operator=(const TestA &ItemCopy)
{
A = ItemCopy.A;
printf("A is: %d!\n",A);
return *this;
}
};
class TestB : public Test... | No conversion operator is needed here, a const TestA& is perfectly capable of binding to an instance of a derived class (because inheritance is public).
|
7,662,802 | 7,662,889 | Regarding the global namespace in C++ | In C++, should we be prepending stuff in the global namespace with ::?
For example, when using WinAPI, which is in C, should I do ::HANDLE instead of HANDLE, and ::LoadLibrary instead of LoadLibrary? What does C++ say about this? Is it generally a good idea, factoring in issues like readability and maintainability?
| As namespaces don't exists in C, don't use ::HANDLE to access HANDLE type.
Using the prepending :: for global namespace is a good idea for readability, you know the type you want to access is from global namespace.
Moreover, if you are in a nested namespace and declare your own HANDLE type (for example), then the compi... |
7,662,977 | 7,663,022 | Casting containers C++ |
Possible Duplicate:
Is it ok to cast a STL container with Base type to Derived type?
This should be a quick question... If I have a container, say an STL list, of a base class, is it possible to casts the entire container to a type of subclass? E.g.
[A inherits from base class B]
list<B*> list1;
list1.push_back(new... | No. std::list<T> and std::list<U> are completely different, incompatible types, if std::is_same<T,U>::value is false, i.e if the type arguments T and U aren't same.
Use std::transform and do appropriate casting in the callback.
|
7,663,071 | 7,663,098 | Numeric limits - is there a limit when multiplying very large constants? | Is there an explicitly defined limit on the size of numbers a compiler can handle when multiplying out constants?
#define val1 1000000000000000
#define val2 <some really really big number>
std::cerr << val1 * val2 << std::endl;
Would this generate an error due to numeric limits in c++ given a sufficiently large value... | It would be treat as an integer and so the maximum integer (defined in limits.h) would apply
If you want a large number use 1000.......0000L to define it as a long.
|
7,663,565 | 7,663,664 | "error: stray '\XXX' in C++ program": Why does this happen? | I'm writing a little program in C++, and come across a strange error:
src/Makefile/Tool.cpp:42:3: error: stray ‘\302’ in program
src/Makefile/Tool.cpp:42:3: error: stray ‘\240’ in program
I'm writing this program in Vim and the corresponding line (showing hidden characters) is:
>--->---std::vector<std::string> { "--de... | "\302\240" is UTF-8 for U+00A0 NO-BREAK SPACE. Vim won’t normally highlight it as anything special, so it’s possible for one to sneak in even if you have 'list' mode enabled.
You can highlight them with:
:set listchars+=nbsp:.
or any character you like.
|
7,663,709 | 7,664,227 | How can I convert a std::string to int? | I want to convert a string to an int and I don't mean ASCII codes.
For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear equations. Now, in saying that, I'm not able to convert a string to an int.
I know that the string will be in either the fo... | In C++11 there are some nice new convert functions from std::string to a number type.
So instead of
atoi( str.c_str() )
you can use
std::stoi( str )
where str is your number as std::string.
There are version for all flavours of numbers:
long stol(string), float stof(string), double stod(string),...
see http://en.cpp... |
7,663,756 | 7,663,952 | Insert spaces to break up even sets of characters within a C++ String | I am trying to write a function that will find any even subsets of characters in a string, and break them in half by inserting an empty space into the string. For example, given the string "AA BBB CCDD", my string should be converted to "A A BBB CC DD".
My breakString() function doesn't seem to work, and I have no idea... | You say it doesn't work, but you don't say how. I can see two immediate
prblems: the first is that you return immediatly when you find the first
word with an even length, so you obviously won't break any following
words; and the second is that if you do want to continue, the insert
will have changed the values of any ... |
7,663,763 | 7,663,832 | Getting png by the coordinates in C++ | I would like to know is there any library for C++ or C which allows to get png-image by coordinates. For example:
I have opened png file, and I need to get only the parf of it which starts from
x = 5
y = 5
w = 10
h = 10
and so on
So what library allows to do such kind of operations?
Thanks on advance
| Using Magic++:
#include <Magick++.h>
using namespace Magick;
void main()
{
Image image;
image.read( "in.png" );
// Crop the image to specified size (width, height, xOffset, yOffset)
image.crop( Geometry(10, 10, 5, 5) );
// Write the image to a file
image.write( "out.png" );
}
|
7,663,820 | 7,663,961 | Calling multiple dll imports with the same method name | I'm importing several unmanaged c++ DLL's into my project however the imported DLLs have the same method name which causes compiler issues. For example;
unsafe class Myclass
{
[DllImport("myfirstdll.dll")]
public static extern bool ReturnValidate(long* bignum);
[DllImport("myseconddll.dll")]
public static... | You could provide any name for your imported function, you should only specify in DllImport the name of the function in it, using EntryPoint property. So you code could look like:
[DllImport("myfirstdll.dll", EntryPoint="ReturnValidate")]
public static extern bool ReturnValidate1(long bignum);
[DllImport("mysecond... |
7,663,880 | 7,663,987 | Should we avoid plural names for variables? | Sometimes it is tempting to name a variable as plural when its a collection of objects like an array or list. Is this okay or should we always stick to singular names for variables? As one example a collection of cars could be called 'cars' or 'car'
Consider another example:
vector< string > students; // it is name... | Plurals are fine -- in fact, i'd go as far as to say expected - when the name refers to a collection of items (ie: a set, list, vector, array, etc). Names like temperature_data can be ambiguous as to whether they refer to a single item or a bunch of them. temperatures, on the other hand, clearly refers to more than o... |
7,664,137 | 7,664,234 | int* variable or int variable | I am working in C++ and have been using pointers a lot lately. I found that there are a few ways to initialize the chunks of memory that I need to use.
void functioncall(int* i)
{
*i = *i + 1;
}
int main(){
int* a = (int*)malloc(sizeof(int));
int az = 0;
functioncall(a);
functioncall(&az);
}
Noti... | int* a = (int*)malloc(sizeof(int));
This allocates memory on the heap. You have to deallocate it on your own, or you'll run into memory leaks. You deallocate it by calling free(a);. This option is most definitely slower (since the memory has to be requested and some other background stuff has to be done) but the memor... |
7,664,529 | 7,664,558 | Converting a string to uint8_t array in C++ | I want an std::string object (such as a name) to a uint8_t array in C++. The
function reinterpret_cast<const uint8_t*> rejects my string. And since I'm coding using NS-3, some warnings are being interpreted as errors.
| If you want a pointer to the string's data:
reinterpret_cast<const uint8_t*>(&myString[0])
If you want a copy of the string's data:
std::vector<uint8_t> myVector(myString.begin(), myString.end());
uint8_t *p = &myVector[0];
|
7,664,561 | 7,664,916 | What synchronization scheme should I choose to avoid deadlock on a realtime, C++/MFC application? | I would like to ask you a question regarding which concurrency facility (CMutex, CSemaphore, CEvent) should I choose, to make a C++/MFC, application multi-threaded.
It is a real time, machine vision application, that is required now to execute concurrently and it needs refactoring, from it's previous single-threaded st... | C must wait for two things to happen, so the most logical thing is that it waits for two auto-reset CEvent objects: one set by A and one by B.
When C is done, A and B must each then wait for a notification. Since there are two threads, and both must wake up, the natural thing is to use another pair of auto-reset CEvent... |
7,664,757 | 7,676,713 | C++ Project Layout seems incorrect, compiler can't find implementation files | I'm writing a C++ Package for later use using Code::Blocks.
The project structure looks like this:
cNormal\
cNormal.cdp
src\
main.cpp # for testing purpose
cnormal_defs.h # important compiler definitions
cnormal_storage.h # includes all .h files from "./storage"
... | I could spot the error now, cnArray.h declared a template class and template classes cannot be implmented in another file than they are declared, because the compiler must know about the implementation when compiling, not when linking.
I have found a workaround on the internet to #include the implementation in the head... |
7,664,807 | 7,665,182 | How to tell the size of font in pixels when rendered with openGL | I'm working on the editor for Bitfighter, where we use the default OpenGL stroked font. We generally render the text with a linewidth of 2, but this makes smaller fonts less readable. What I'd like to do is detect when the fontsize will fall below some threshold, and drop the linewidth to 1. The problem is, after al... | This should be determinable rather easily. The font's size in pixels just depends on the modelview transformation (actually only the scaling part), the projection transformation (which is a simple orthographic projection, I suppose) and the viewport settings, and of course on the size of an individual character of the ... |
7,665,021 | 7,665,050 | C++ Member Initialization List | Please explain how to use member initialization lists.
I have a class declared in a .h file and a .cpp file like this:
class Example
{
private:
int m_top;
const int m_size;
...
public:
Example ( int size, int grow_by = 1 ) : m_size(5), m_top(-1);
...
~Example();
};
I'm initializing m_size on ob... | This is the initialization list :
Example::Example( int size, int grow_by) : m_size(5), m_top(-1)
{
... some code here
}
and it should be done only in the cpp file.
Don't you get an error when you do it like you did in the header in your example?
|
7,665,060 | 13,322,043 | Qt Creator and static libraries | I'm quite a newbie with C++ and maybe that's a very stupid question, but how do one include a header from a static linked library?
I've created a static library in Qt Creator with the following .pro file:
QT -= gui
TARGET = Foobar
TEMPLATE = lib
CONFIG += staticlib
SOURCES += thefoobar.cpp \
sub/subbar.cpp
HEADER... | Check where you have placed your "thefoobar.h" header file . Place it in the "extstaticlibs/" folder .
|
7,665,132 | 7,665,161 | Inheritance constructors: Converting from C# to C++ | I'm coming from a C# background where I would write a class and constructor like this:
public class Grunt : GameObject
{
public Grunt()
: base()
{
// do stuff
}
}
How do I write the constructors inheritance in C++? In both the header and the source. I know you don't have the 'base' keyword... | class Grunt : public GameObject
{
Grunt()
: GameObject() // Since there are no parameters to the base, this line is actually optional.
{
// do stuff
}
}
And strongly consider getting one of the fine C++ books at The Definitive C++ Book Guide and List
|
7,665,346 | 7,665,415 | Read text file step-by-step | I have a file which has text like this:
#1#14#ADEADE#CAH0F#0#0.....
I need to create a code that will find text that follows # symbol, store it to variable and then writes it to file WITHOUT # symbol, but with a space before. So from previous code I will get:
1 14 ADEADE CAH0F 0 0......
I first tried to did it in Pyt... | This looks like a job for std::locale and his trusty sidekick imbue:
#include <locale>
#include <iostream>
struct hash_is_space : std::ctype<char> {
hash_is_space() : std::ctype<char>(get_table()) {}
static mask const* get_table()
{
static mask rc[table_size];
rc['#'] = std::ctype_base::space;
retur... |
7,665,402 | 7,665,972 | Shouldn't VARCHAR data be converted to char * (MSSQL OLE DB)? | In a C++ program, I am trying to read data from MSSQL database using OLE DB. The column I am trying to read is a VARCHAR type. The data in the column is imported from a multi-value database. Sometimes the data in the column has a delimiter in it. The delimiter is a value marker (0Xfd). I covert the data read from the t... | The WideCharToMultiByte converts from UTF-16, yet there is no such thing as 0xFD character in UTF-16. All characters are encoded as at least 2 bytes. Did you actually mean 0x00FD (or even 0xFD00)?
Also, UTF-8 (your "target" encoding since you specified CP_UTF8) does not guarantee that all characters will be encoded in ... |
7,665,761 | 7,665,781 | "Cannot convert 'MyClass' to 'bool'" Error in Template Programming | I am playing around with templates and have tried the following but get 'Cannot convert 'MyClass' to 'bool' error?
#include "Unit2.h"
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a > b) ? a : b;
return (result);
}
int main () {
MyClass k1( 10, "A" );
MyClass k2( 50, "B" ... | Your > operator should return a bool, not a MyClass reference.
|
7,665,912 | 7,665,940 | Double include solution? | In C++, I have a problem with a double include:
File stuffcollection.h
#pragma once
#ifndef STUFFCOLLECTION_H
#define STUFFCOLLECTION_H
#include "Stage.h"
class Stuffcollection {
public:
bool myfunc( Stage * stage );
};
#endif // STUFFCOLLECTION_H
File stage.h:
#pragma once
#ifndef STAGE_H
#define STAGE... | You have a Circular Dependency. Instead use Forward Declaration in Stuffcollection.h
#pragma once
#ifndef STUFFCOLLECTION_H
#define STUFFCOLLECTION_H
//#include "Stage.h" //<------------------Don't Do This
class Stage; //<------------------Do This
class Stuffcollection {
public:
bool myf... |
7,665,978 | 7,672,775 | Error when compiling gcc 4.6.1 C++0x threading code on MacOSX Lion | When compiling the following code:
#include <iostream>
#include <thread>
using namespace std;
void hello()
{
cout << "Hello World!" << endl;
}
int main()
{
cout << "starting" << endl;
thread t(hello);
t.join();
cout << "ending" << endl;
return 0;
}
using:
$ g++-4.6.1... | See http://gcc.gnu.org/PR50196 - Mac OS X doesn't support some parts of pthreads that we rely on. Building the latest version won't help, but it might be fixed for GCC 4.7
|
7,666,144 | 7,666,318 | Making C++ DLL for C# | I have made a very simple Dll like this:
extern "C"
{
__declspec(dllexport) int Try(int v)
{
return 10 + v;
}
}
Then I want to use it in my C# app:
class Program
{
[DllImport("TestLib.dll")]
public static extern int Try(int v);
static void Main(string[] args)
{
Console.WriteLine("Wyn... | The error message you've got contains a good advice indeed:
Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
You should have the same calling convention specified on both sides (C++ dll and C# assembly). In C++ you can specify it by prepending function de... |
7,666,344 | 7,674,214 | Are empty macro arguments legal in C++11? | I sometimes deliberately omit macro arguments. For example, for a function-like macro like
#define MY_MACRO(A, B, C) ...
I might call it as:
MY_MACRO(, bar, baz)
There are still technically 3 arguments; it's just that the first one is "empty". This question is not about variadic macros.
When I do this I get warnings... | If I understand correctly, empty macro argument is allowed since C99 and
C++0x(11).
C99 6.10.3/4 says:
... the number of arguments (including those arguments consisting of
no preprocessing tokens) shall equal the number of parameters ...
and C++ N3290 16.3/4 has the same statement, while C++03 16.3/10 mentions:
..... |
7,666,636 | 7,666,770 | C vs C++ initialization of static locals | I have the following code in both C and C++
static void callback(char const* fname, int status)
{
static char const* szSection = fname;
//other stuff
}
In C++ this compiles fine without warning or error. In C I get the compilation error "initializer is not constant". Why does it differ between the two? I'm using t... | Because the rules are different in C and C++.
In C++, static variables inside a function get initialized the first time that block of code gets reached, so they're allowed to be initialized with any valid expression.
In C, static variables are initialized at program start, so they need to be a compile-time constant.
|
7,666,784 | 7,666,816 | Expected declaration specifiers or '...' before bool | I wrote in C function:
void func(int count,bool infini){
//...
}
I try compile this code with Code Blocks, (GCC) spike:
"expected declaration specifiers or '...' before bool"
.
Where is bug?
| Chances are that you are compiling in C mode. C does not have bool. Use int instead or include stdbool.h to get a #define of bool (only C99) or create a typedef / #define yourself (if your compiler doesn't have or you don't want to use stdbool.h. But GCC provides this header).
Alternatively in C99 code you can use _Bo... |
7,666,928 | 7,667,176 | IntelliSense Including Things that Shouldn't be Included | I'm working on a project in Visual Studio 2010. My project is not supposed to be limited to Windows, however, one of the files is OS-dependant.
For this reason, I have #include <windows.h> in only one of the .cpp files. No other file includes this .cpp files. Therefore, logically, the windows.h header should be invisib... | Quoting Andy Rich, a Microsoft employee who works on VC++, from a comment on this blog article: Troubleshooting Tips for IntelliSense Slowness
The browsing database will find all source files that are somehow included in your project, either directly or as a result of other #include directives. This is not configurab... |
7,667,077 | 7,667,137 | do need to use mutex lock? | Simple edition: In a C++ program I'm using two different threads to work with some integer variable. but I'm sure one is always writing some value into it and the other one is only reading That. do I still need to use mutex lock when reading/writing data?
Now details : The main idea is that first thread generates some ... | No the read and write are not atomic, You will need to synchronize it using some synchronization mechanism.
Also, You MUST mark the shared integer as volatile, otherwise the optimizer might think the variable is never updated in one of your threads.
gcc allows you to do atomic operations on int‘s, long‘s and long long‘... |
7,667,191 | 9,754,529 | What's the memory limit in WinXP when getting a callback from a C++ DLL in C#? | I have a C# application that uses an unmanaged C++ DLL. I've found a crash that only happens in WinXP (not Win7) when the memory I'm passing back from the C++ DLL is too big.
The basic flow is that C# starts an operation in the C++ DLL by calling a start function, in which it provides a callback. The C++ DLL then perfo... | So it eventually turned out I was being an idiot. In order to make the log large but speed the testing up I was clicking on the cancel button, which called a function in the C++ DLL that stopped execution and called the callback function with an 'abort' error and whatever log had already been recorded. But when I did t... |
7,667,198 | 7,668,123 | Assertion `in' failed - c++ | The following is part of client program for a fraction class. I wrote the class and now am testing it with the given client program. When I try to run it, I get this error:
Assertion 'in' failed.
Code:
bool eof(ifstream& in);
cout << "\n----- Now reading Fractions from file\n";
ifstream in("fraction.data");
asse... | So I finally got it. I just need to move my "fraction.data" file to main project directory. Before, I had it in the source folder within the directory.
|
7,667,224 | 7,667,330 | memory allocation for array of strings | As far as I know arrays are allocated statically but strings are dynamic as their length frequently changes during runtime.
What happens when I define an array like this:
std::string array[] = {"abc", "defghi", "jk", "lmnop", "qrstuvwxyz"};?
Is there a limited amount of memory allocated for every string? Or is the arra... | Don't overthink things. When you say T x[N];, you declare an automatic (i.e. scope-local) array. This is very similar to just declaring T x1;, T x2;, ..., T xN;. An instance of std::string always occupies the same, small size in its declaration context (e.g. on the stack); it is only the memory which it manages (by def... |
7,667,272 | 7,667,598 | Use STL to populate a vector<T> from map<T,Z>'s keys | map<T,Z> m= ...;
vector<T> v;
v.reserve(m.size);
for(map<T,Z>::iterator it=m.begin();it!=m.end();++it)
{
v.push_back(it->first);
}
Is there a nicer 1-line version using some STL function(s)?
edit: not using c++11!
| Portable:
struct SelectKey {
template <typename F, typename S>
F operator()(const std::pair<const F, S> &x) const { return x.first; }
};
std::transform(m.cbegin(), m.cend(), std::back_inserter(v), SelectKey());
I think some implementations of STL have a non-standard extension called select1st, which is the equiva... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.