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,185,481 | 7,185,593 | Instantiate a template for a vector | #include <iostream>
#include <vector>
using namespace std;
template <typename nameOfTheVariableTypeA,
typename nameOfTheVariableTypeB> nameOfTheVariableTypeB functionX
(nameOfTheVariableTypeA argA,
(nameOfTheVariableT... | First off, there's a superfluous parenthesis:
template <typename nameOfTheVariableTypeA,
typename nameOfTheVariableTypeB> nameOfTheVariableTypeB functionX
(nameOfTheVariableTypeA argA,
/*(*/nameOfTheVariableTypeB arg... |
7,185,732 | 7,185,880 | Evaluation order of overloaded operator |? | 5.15 Logical OR operator in the standard says the following:
Unlike |, || guarantees left-to-right evaluation;
Does this mean somewhere I cannot locate in the standard, | is defined to evaluate right-to-left, or that it is implementation-defined? Does this vary when the operator is overloaded? I wrote a quick program... | As others said, it means that the order of the evaluation of the two sides is unspecified. To answer your other questions -
I've also considered that I may be running into the multiple changes between sequence points rule (and thus undefined behavior)
No, your case does not modify foo in between two adjacent sequence... |
7,185,831 | 7,186,373 | What this error means and how to solve it? | I am trying to build a C++ code using NDK in android. I have a method which has a parameter vector < vector <float> > coordinates
Everything builds fine until I write this line inside my method
vector<float> firstPoint = coordinates.at(0);
I start getting this error
D:/eclipseworkspace/myLibProject/obj/loc... | When I changed
vector<float> firstPoint = coordinates.at(0);
to
vector<float> firstPoint = coordinates[0];
it started compiling..... :s y?
|
7,185,958 | 7,186,038 | Winsock 2.0 Will Not Connect to Public IP Address | So I am trying to build a simple text IM program to get into the wonderful world of networking. I have written 2 programs using Winsock 2.0 with C++: a server and a client. I have specified a UDP connection via the socket creation:
SOCKET Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
Everything works when I try t... | Most likely the public IP address you have is owned by your network router appliance. It needs to be configured to pass traffic onto your computer
public IP internal router
address +--------+ IP address +---------+
v | | v | |
----------+ router +--------------+ de... |
7,186,248 | 7,186,321 | how to declare and define a time data? | I have a class that needs to contain a time variable. How to do that? I would like to specify that I communicate with a server and as a response at time section I receive for example: 2011-07-01T14:32:39+02:00 .APPRECIATE. THX
P.S I would like to use the C++ API.
| There are several solutions each with another drawback. One would be to just calculate the timestamp and save it as a number. Another would be to use boost date_time (which I would prefer if you can introduce a dependency to boost).
It all very much depends on what you need to do with the time. If you only need to save... |
7,186,274 | 7,186,398 | C++ pointer array initialization help | I had trouble with initializing arrays of pointers. What I found out compiling with gcc c++ (4.6.0) is:
MyClass** a = new MyClass*[100];
Does not always initalize the array of pointers. (most of the time it did give me an array of null pointers which confused me)
MyClass** a = new MyClass*[100]();
DOES initialize all... | This value-initialization is standard C++.
The relevant standardeese is in C++98 and C++03 §5.3.4/15. In C++98 it was default-initialization, in C++03 and later it's value initialization. For your pointers they both reduce to zero-initialization.
C++03 §5.3.4/15:
– If the new-initializer is of the form (), the item i... |
7,186,341 | 7,186,409 | How come a pointer to a derived class cannot be passed to a function expecting a reference to a pointer to the base class? | Sorry for the long title but I did want to be specific.
I expected the following code to work but it doesn't and I can't figure out why :/
#include <cstdio>
#include <cassert>
class UniquePointer
{
public:
void Dispose()
{
delete this;
}
friend void SafeDispose(UniquePointer*& p)
{
... | Imagine it were legal. Then you could write code like this:
class Animal : public UniquePointer
{
};
void Transmogrify(UniquePointer*& p)
{
p = new Animal();
}
void Foo()
{
Building* b = nullptr;
Transmogrify(b);
b->SetBuildingType(0); // crash
}
Observe that you have violated the type system (you pu... |
7,186,623 | 7,186,661 | Where exactly is the boundary between a preprocessor and a compiler? | According to various sources (for example, the SE radio episode with Kevlin Henney, if I remember correctly), "C with classes" was implemented with preprocessor technology (with the output then being fed to a C compiler), whereas C++ has always been implemented with a compiler (that just happened to spit out C in the e... | This is an interesting question. I don't know a definitive answer, but would say this, if pressed for one:
A preprocessor doesn't parse the code, but instead scans for embedded patterns and expands them
A compiler actually parses the code by building an AST (abstract syntax tree) and then transforms that into a differ... |
7,186,705 | 7,186,790 | How to define a template overide's function in a non-inline way | Hi so I have a template class called Body, that takes a single sf::Drawable descendant as a template argument, and i'm trying to overide the Render() function only for the case that the template argument is a sf::Shape.
How do i do this in a non-inline way? The code works when I define the function inside the class, a... | You mean like this?
template <typename T>
struct Foo {
int frob() const;
};
// Note: Member function specializations do not require
// full class specializations.
template <typename T>
int Foo<T>::frob() const { return 42; }
template <>
int Foo<float>::frob() const { return 0xbeef; }
#include <iostre... |
7,187,072 | 7,192,561 | Handling WM_PAINT in a Subclassed CStatic Control | I created a custom control whose class has CStatic as base class. Currently I handle the drawing using WM_PAINT event. But there is a strange behavior. When I re-enable the window after disabling it using CWnd::EnableWindow function, it refuses to draw what I written in OnPaint function. It draws the static control ins... | Here is exactly what I have written:
class CMyStatic : public CStatic
{
DECLARE_MESSAGE_MAP()
public:
void OnPaint(void);
};
BEGIN_MESSAGE_MAP(CMyStatic, CStatic)
ON_WM_PAINT()
END_MESSAGE_MAP()
void CMyStatic::OnPaint(void)
{
CPaintDC dc(this);
CRect rect;
GetClientRect(&rect);
dc.FillSo... |
7,187,078 | 7,187,119 | Enforce use of Getter / Setter within same class (C++) | Is there a way in C++ to enforce the use of getters or setters WITHIN the class?
class C{
private:
int x; // should only be Changed by setX();
private:
setX(int i){
(...) // enforce some complicated invariantes
x = i;
};
m(){
x = 5; // should not not allowed
}
}... | You can take advantage of composition like this:
class C_int
{
public:
void setX(int i)
{
/* enforce invariants */
x = i;
}
private:
int x;
};
class C
{
pulbic:
void m()
{
x.setX(5);
// x.x = 5; // Won't compile.
}
private:
C_int x;
};
But I find it od... |
7,187,860 | 7,187,941 | Compile C#, so that it runs with the speed of C++ | Alright, so I wanted to ask if it's actually possible to make a parser from c# to c++.
So that code written in C# would be able to run as fast as code written in C++.
Is it actually possible to do? I'm not asking how hard is it going to be.
| What makes you think that translating your C# code to C++ would magically make it faster?
Languages don't have a speed. Assuming that C# code is slower (I'll get back to that), it is because of what that code does (including the implicit requirements placed by C#, such as bounds checking on arrays), and not because of ... |
7,188,092 | 7,188,856 | Static arrays at compile time in C++ | I was wondering if its possible to make the following answer more generic, in the sense that the type of the array be templated instead of just unsigned:
I've enclosed the whole thing in a struct like so:
template<typename ArrayType>
struct Array
{
template<ArrayType... args> struct ArrayHolder {
static const Arr... | It helps if you indent the struct. The problem is that you are defining the data static member variable inside the Array struct. But it should be at namespace scope:
template<typename ArrayType>
struct Array
{
template<ArrayType... args> struct ArrayHolder {
static const ArrayType data[sizeof...(args)];
... |
7,188,158 | 7,188,387 | Recognize if removable drive was inserted | I have a piece of code to check the removable drives connected to the computer. But I have to check when the drive is available or inserted into the USB port.Should I write a while loop constantly checking for the drive with certain ID to become available? If I make it into a windows service, do I have to do the same i... | Create a hidden window and use it to listen for WM_DEVICECHANGE messages.
Whatever you do, don't poll. That's horribly wasteful and inefficient.
|
7,188,826 | 7,189,138 | Default type assumption by a template function | Example: Assuming f to be a template function, having two arguments:
f (1, 2) In this call, does the template function assume that its arguments are int, or short, or anything else?
EDIT 1:
The template function declaration:
template <typename dataTypeA, typename dataTypeB> dataTypeB functionX (dataTypeA argA, dataType... | As @David already said, as far as your question is concerned, there's no such thing as "making assumptions". The literals simply have types, which are the types that a function template may use for type deduction. Remember that conversions considered as part of the template matching, though!
So, let's say you have this... |
7,189,157 | 7,189,692 | Prevent inheriting operator new and delete | (I did scan, but couldn't find anything similiar, if dupe please close).
Is there a way to prevent these two operators from being inherited? For example:
struct foo{
static void* operator new(std::size_t) {
// special
}
static void operator delete(void* p, std::size_t) {
// special
}
};
struct ba... | You could define an intermediate foo which calls global new/delete again and derive from that.
class foo_without_new : public foo
{
protected:
foo_without_new(){} // only derived types should be able to construct foo_without_new!
public:
void *operator new(size_t sz)
{
return ::operator new(sz);
}
void... |
7,189,420 | 7,189,443 | One VS2010 bug ? Allowing binding non-const reference to rvalue WITHOUT EVEN a warning? | string foo() { return "hello"; }
int main()
{
//below should be illegal for binding a non-const (lvalue) reference to a rvalue
string& tem = foo();
//below should be the correct one as only const reference can be bind to rvalue(most important const)
const string& constTem = foo();
}
GCC is th... | That is a known issue/feature of the VS compilers. They have always allowed that and there does not seem to be any push into removing that extension.
|
7,189,801 | 7,190,787 | Implementing a multivariate gaussian probability density function for >2 dimensions in C++ | I'm working on implementing a probability density function of a multivariate Gaussian in C++, and I'm stuck on how to best handle the cases where dimension > 2.
The pdf of a gaussian can be written as
where (A)' or A' represents the transpose of the 'matrix' created by subtracting the mean from all elements of x. In t... | I'm a little bit out of my element here, but some thoughts:
First, from a programming view, the stock answer is "profile." That is, code it up the clearer way first. Then profile your execution to see if optimizing is worthwhile. IMHO it's probably clearer to use a matrix library to keep closer to the original math.... |
7,189,813 | 7,189,848 | C++ all differences between 'struct' and 'class'? |
Possible Duplicate:
What are the differences between struct and class in C++
I used to think that the only differences between C++ classes were the private-by-default class member access modifiers and the laid-out-like-C guarantee.
It turns out I was wrong, because this code doesn't compile:
class { int value; } var... | You can use {} initializer for aggregates only1 and the first one is not an aggregate, as it has one private data member.
The Standard says in section §8.5.1/1,
An aggregate is an array or a class (clause 9) with no user-declared
constructors (12.1), no private or protected non-static data members
(clause 11), no... |
7,190,026 | 7,190,054 | constructor or copy constructor? | In the book Generic Programming and the STL (Chinese edition), it says:
X x = X() will call the copy constructor.
It seems a little weird to me. And I write a test program like this
#include <iostream>
class Test {
public:
Test() {
std::cout << "This is ctor\n";
}
Test(const Test&) {
... | Nomimally yes, a temporary is default-constructed, and then the copy constructor is invoked to copy it into your object t.
However, in practice the copy can be optimised out — even though it has side effects (the console output):
[n3290: 8.5/16]: [..] In certain cases, an implementation is
permitted to eliminate the... |
7,190,424 | 7,190,915 | C++ linking and template specializations | I'm studying the behavior of the C++ linker with respect to template specializations. I'm using Microsoft Visual C++ 2010 for these experiments. I don't know if the behavior is the same with other toolchains (e.g. gcc).
Here's a first code snippet:
// bar.cpp
template <typename T> int foo() { return 1; }
int bar() { r... | You are actually violating a C++ rule here (emphasis mine):
14.7.3 [temp.expl.spec]:
6/ If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take pl... |
7,190,673 | 7,192,737 | How to read in only a particular number of characters | I have a small query regarding reading a set of characters from a structure. For example: A particular variable contains a value "3242C976*32" (char - type). How can I get only the first 8 bits of this variable. Kindly help.
Thanks.
Edit:
I'm trying to read in a signal:
For Ex: $ASWEER,2,X:3242C976*32
into this structu... | you could..
convert your hex value in canID to float(depending on how you want to display it), e.g.
float value1 = HexToFloat(m_pg.canID); // find a conversion script for HexToFloat
CString val;
val.Format("0.3f",value1);
the garbage values aren't actually being stored in the structure, it only displays it as so, as ... |
7,190,708 | 7,190,827 | c++ pointer on 64 bit machine | I am using c++ under 64 bit linux, the compiler (g++) is also 64 bit. When I print the address of some variable, for example an integer, it is supposed to print a 64 bit integer, but in fact it prints a 48 bit integer.
int i;
cout << &i << endl;
output: 0x7fff44a09a7c
I am wondering where are the other two bytes. Loo... | The printing of addresses in most C++ implementations suppresses leading zeroes to make things more readable. Stuff like 0x00000000000013fd does not really add value.
When you wonder why you will normally not see anything more than 48bit values in userspace, this is because the current AMD64 architecture is just define... |
7,190,941 | 7,190,991 | Does boost::interprocess::named_mutex need to be stored in shared memory? | I want to use boost::interprocess to perform synchronization across multiple processes; in the specific I want to to use boost::interprocessnamed_mutex under Linux OS ( I am using g++ ) .
Do you know if each instance of this class has to be stored in shared memory like the simple boost::interprocess::mutex?
|
Do you know if each instance of this class has to be stored in shared memory like the simple boost::interprocess::mutex?
The "named" objects don't have to be in the shared memory. See this example in the Boost.Interprocess documentation.
|
7,190,952 | 7,190,979 | Access child members within parent class, C++ | I am facing a situation where I need to access child member variables inside the parent class. I know this is against OO principles but I have to deal with a scenario where hundreds of classes are inheriting from one and along the way half of them stopped using one of the parents variable, and declared and used their o... | The only clean way is to use the virtual function approach.
If the Parent class has at least one virtual function (not necessarily DoSomething), there's also a yucky way to do it:
void DoSomething() {
if (Child1* child = dynamic_cast<Child1*>(this)) {
child->childMember = 0;
} else if (Child2* child = d... |
7,190,987 | 7,196,462 | Conversion of C++/CLI array of strings to native C++ char** | In C++/CLI, What's the most efficient way to convert an array of strings to native char**?
I am doing this:
array<String^>^ tokenArray = gcnew array<String^> {"TokenONE", "TokenTWO"};
int numTokens = tokenArray->Length;
char** ptr = new char* [numTokens];
for(int i = 0; i < numTokens; i++)
{
// See: http://... | Apart from the problem with pinned pointers going out of scope before being passed to someNativeFunction(), the code can be simplified for better clarity especially if you're using MSVC2008 or newer. See this page for information on how to convert a single string (extending to an array should be trivial).
Edited:
If yo... |
7,191,093 | 7,191,224 | How to measure total STL container memory consumption? | As in the title: given an object of type of some STL container (e.g. std::vector<int> or std::set<MyClass>) I would like to know their memory consumption --- that is --- how much memory is consumed to store the elements, the auxiliary data for each element and the container size. I assume that the objects stored do not... | Create your own STL allocator and track the size of the memory requests placed to it, then jsut add the size of the container itself. This article gives a good overview of creating one.
|
7,191,159 | 7,192,819 | No appropriate default constructor available and no default constructor exist | I am new to C++ and trying to write a "Date Class" program that make some calculations on dates.
These two errors appear to me:
error C2512: 'Date' : no appropriate default constructor
IntelliSense: no default constructor exists for class "Date"
In the line that i have declare an object from the class:
int _tmain(int... | Do this:
The constructor in the .h file:
public:
Date(int=0, int=0, int=0);
The implementation:
Date::Date(int d, int m, int y)// DEFAULT CONSTRUCTOR
{
// Initialize data of this class
}
The prototype/declaration of method should mention the default arguments, not the implementation.
|
7,191,266 | 7,191,335 | Passing 2-D array with dynamic size between functions in C/++ | This is "popular" question so I already checked the similar threads but still didnt resolve my issue.
How can I declare 2-D array to hold "strings" - I need array of array of chars AFAIK - and use it as argument to 5 functions one after another where I can pass it by reference and update the content dynamically so foll... | One possible solution in C is as follows:
char **p_strings = calloc(num_strings, sizeof(*p_strings));
for (i = 0; i < num_strings; i++)
{
// Allocate storage for the i-th string (always leave room for '\0')
p_strings[i] = calloc(len_string[i]+1, sizeof(*p_strings[i]));
}
...
// Call a function
my_function(p... |
7,191,393 | 7,192,380 | Which XSLT Processor for C++? | I started off with Xalan for C++, but that really seemed like overkill for this project. I will have an XML file in memory, there is one stylesheet to run it through... and that's pretty much it.
The input XML and the stylesheet are all in-house and validated for integrity before it gets to my code so I really just wan... | C libraries integrate well will C++ code. The only issue is if the library itself is compiled as C it will not have C++ style name mangling. This can easily be worked around by ensuring that all the headers have the extern "C" { ... } wrappers. Most C libraries will already have this together with the #ifdef __cplusplu... |
7,191,857 | 7,620,838 | How to log key events from non-standard keys under Windows 7 | I have a two-fold problem and I'm familiar with neither branch of it.
Background:
I've purchased a new laptop from MSI. As a feature I've never seen before, the CD-drive does not have a mechanical eject button mounted on the drive. Instead, a digital eject button is part of the "smart-bar" above the Function Keys. Unfo... | I encountered this same problem myself. I don't know whether or not you are familiar with autohotkeys, but used it to write a script to replace s-bar.
AutoHotKey (AHK) is a open source macro-creating and scripting language for Windows with a ton of functionality. You can run the scripts through the program itself or co... |
7,191,940 | 7,194,834 | QT C++ - QNetworkAccessManager help needed! Class problem | I'm trying to download a page from a server to my QT program, but I've been searching ways to do it and they don't really work a lot. I'm not an expert in QT/C++, so be kind :)
Well.. So far I come with this code:
[OLD CODE] - Check the updated code bellow!
http.cpp
#include "http.h"
http::http(QObject *parent) :
... | Your http or http2 object is destroyed at the end of the constructor, because it is allocated locally.
You should at least allocate it dynamically:
http2 *h = new http2(this);
If you want to reuse it, you can also declare it as a member of tcpserver, instead of using a local variable. If not, you should destroy it so... |
7,192,006 | 7,192,095 | removing unnecessary code at compile time | I use the CImg library to write plugins for an image-editing software I created.
The problem is that when I include CImg, size of the plugins explodes from 200kb up to 2Mb!
But in this particular case I only use 5% of CImg code!
So my question is: is there a way to remove unnecessary code at compile time, so the final ... | Make sure you are compiling with full optimisations (or just -Os which is size optimisation) and stripping debug symbols with strip -s. That can take up a lot of space.
Also it could be that while you are only using 5% of the CImg code, the 5% you use is using the other 95% internally. Pretty much the best you can do i... |
7,192,069 | 7,192,124 | polymorphic C++ references | I was wondering how you can do polymorphism with references, as opposed to pointers.
To clarify, see the following minimal example:
class A;
class B {
public:
A& a; ///////////////// <- #1
B();
void doStuff();
};
class A {
public:
virtual void doSmth() = 0;
};
void B::doStuff() {
a.doSmth();
}
... | There's nothing odd. Polymorphisms works both for pointers and references:
struct Base { };
struct Derived : Base;
void foo(Base &);
int main() {
Derived x;
foo(x); // fine
}
You're conflating this with another issue, namely creating a reference to a dynamic object:
T * pt = new T;
T & rt = *pt;
T & x = *new... |
7,192,274 | 7,192,333 | Can ForwardIterator and OutputIterator in C++ standard algorithms be the same? | Can the 'streaming' algorithm like std::transform or std::partial_sum read from and write to the same place?
For example the following code works in gcc but I'm not sure if it is not 'just accident' and compiler is free to break the code in order to optimize it.
#include <algorithm>
#include <iostream>
#include <numeri... | Yes, this would work fine. You would overwrite your source for the same amount of answer elements.
For example,
int square(int x) { return x*x; }
std::transform(vec.begin(), vec.end(), vec.begin(), square);
Would square each number in vec in their place.
|
7,192,306 | 7,193,550 | Why does comparing a member function pointer to NULL generate a warning? | The following bit of code compiles without warning for Windows, Mac and iOS:
class MyClass {
SomeOtherClass * m_object;
void (SomeOtherClass::*m_callback)();
public:
MyClass(SomeOtherClass * _object,void (SomeOtherClass::*_callback)()=NULL) :
m_object(_object),m_callback(_callback) {}
void DoSt... | I don't think you're allowed to compare 0 (or NULL) with member function pointers, especially since they might not be actually pointers (when the function is virtual, for instance).
Personally, I'd rewrite the if test without the comparison, e.g.:
void DoStuff() {
if (m_callback) {
(m_object->*m_callback)()... |
7,192,370 | 7,193,059 | How to run C++ library with OpenCV on the other computer (linux)? | I wrote a small project using C++, OpenCV 2.2 and g++ in Ubuntu 11.04. I need to make a library (.so would be better), but I want it to run on the other computer, without OpenCV installed.
I've tried to build dynamic library using -shared and -fPIC flags for g++, and copied OpenCV .so libs to the working directory. A... | It is possible to build OpenCV without dependencies from system libraries. To turn of all the dependencies for OpenCV 2.2 on Linux you can run cmake with following arguments:
cmake -DWITH_1394=OFF -DWITH_CUDA=OFF -DWITH_EIGEN2=OFF -DWITH_FFMPEG=OFF -DWITH_GSTREAMER=OFF -DWITH_GTK=OFF -DWITH_OPENEXR=OFF -DWITH_PVAPI=OFF... |
7,192,425 | 7,192,917 | C++ DispInvoke fails to find member | The scenario is this:
I have a COM object to ask questions. Name it ICom.
The COM object requires me to implement an IDispatch , descendant of , say, IComEvents, that notifies me for events.
I implement an IDispatch and connect it to the COM interface.
So far so good. My IComEvents descentant's Invoke() is called whe... | Is IComEvents a dual interface or a dispinterface? If it is a pure dispinterface it doesn't have a vtable. DispInvoke requires the interface to have a vtable (ie that it is a dual interface).
|
7,192,506 | 7,192,545 | Changing a function to return a pointer | I'm quite new to C++ and I have written the class and function below:
class Person {
public:
boost::shared_ptr<Details> GetDetails(const std::string& name) const;
...
private:
std::map<std::string, boost::shared_ptr<Details> > map;
...
};
inline
boost::shared_ptr<Details>
Person... | You want to return the address of a shared pointer, so you need to use &, not *.
Note that dealing with pointers to shared-pointers is a little bit weird. Why not just return an empty shared-pointer if you can't find the item?
|
7,192,544 | 7,197,694 | Dynamic Forking of Win32 EXE | http://www.security.org.sg/code/loadexe.html
http://pastebin.com/QFHASx75
I've compiled this but can't get it to work properly, It runs fine and shows no errors in the console
console output:
C:\~\~\Documents\Visual Studio 2010\Projects\loadEXE\Debug>loadEXE.exe AcceleratedC++Exe_2-0.exe
Original EXE loaded (PID = 4068... | The code modifies the entrypoint of the new process like this:
ctx.Eax = (DWORD)v + inpeXH->addressOfEntryPoint;
On Windows x64 (both 64-bit and wow64) this doesn't work anymore, I'm actually surprised this trick was usable for so long.
To quickly fix this, you'd need to write a small sample project that starts a susp... |
7,192,580 | 7,192,603 | Send struct over c sockets | I am building a UDP chat app. Is it safe sending C struct over c socket and on the other end memset received data? All data in struct is nullpaded with memset, so I assume the size of the struct is always constant. What problems may I encounter?
How are more experienced programmers approaching this?
| Yes it is safe BUT we should caveat this first. You may run into a problem if you are passing it between disparate platforms and then you need to worry about byte ordering/packing (amongst a host of other issues possibly). That being said, if you don't know how to do any of this, then it is not safe to assume that you ... |
7,192,596 | 7,193,613 | Collection of template-heterogeneous types | I have a bunch of boost::property_maps defining costs of edge traversal in a graph. I'm executing an algorithm with differently weighted combinations of these maps, currently by manually doing totalcost = weight1*weight1_factor + weight2*weight2_factor + .... The number of property maps is rising though, and it's becom... | I would advise you to create a boost::tuple with property maps and factors.
Given that in your context, you have (propertymap_i, weight_i) for each i, create an aggregation class which uses this tuple (as a template parameter for the aggregation class) to compute the needed value, when asked.
You may either use operato... |
7,192,855 | 7,192,905 | How to overload "operator %" in c++ | I want to overload the % operator in c++, in order to avoid editing a huge block of code by hand. I tried this:
static float operator %(const float& left, const float& right);
In my header, but it wont work because "nonmember operator requires a parameter with class or enum type".
I'm relatively new to C++, what am I ... | Operator overloads must have at least one of their arguments as a user-defined type. So you cannot do this.
|
7,193,174 | 7,249,052 | Create TNotifyEvent in C++ for use at Application level | I need to hook on to the Application's OnDeactivate event in C++ Builder. So I need to write my own function to run when the OnDeactivate event fires for the application, but I don't know where or how to define that function.
Ideally I would like my code to look something like this:
WINAPI _tWinMain(HINSTANCE, HINSTAN... | You are trying to assign a stand-alone function where a non-static class method is expected instead. You have two choices:
1) Move your event handler into a helper class:
class Helper
{
public:
void __fastcall myFunction(TObject *Sender)
{
// ... do stuff
}
};
WINAPI _tWinMain(HINSTANCE, HINSTANCE,... |
7,193,182 | 7,193,232 | C Bitwise Operation Question | Can someone help me understand whats going on with this code. It looks like it is making an integer from an array of bits. Im not sure how its doing that. Why is there a bitwise & operation on OxFF? Inst this just going to produce the same result?
//first take the first 4 bytes read out of the socket into an array and... | That's a very long-winded way of just converting four 8-bit bytes into a 32-bit long.
The anding with 0xff is just ensuring that only the lower 8 bits of each value are used (0xff == binary 11111111).
The bit-shifting (in multiples of 8) is just to get each character into the right position.
The whole thing could be re... |
7,193,197 | 7,195,779 | Is there a graceful way to handle toggling between fullscreen and windowed mode in a Windows OpenGL application? | I'm wondering if it's possible to toggle back and forth between fullscreen mode and windowed mode in an OpenGL window(I'm writing for Windows using C++ and win32), without destroying the OpenGL context, and thus having to reload assets(Textures, VBOs, etc) in the process?
This is undesirable because it introduces a del... | Basically it's just resizing the window and specifying flags that the border is invisible.
SetWindowLongPtr(hWnd, GWL_STYLE,
WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
MoveWindow(hWnd, 0, 0, width, height, TRUE);
to set it back:
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = wi... |
7,193,460 | 7,193,500 | Issue with vector<bool> and printf | #include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, const char *argv[])
{
vector<bool> a;
a.push_back(false);
int t=a[0];
printf("%d %d\n",a[0],t);
return 0;
}
This code give output "5511088 1". I thought it would be "0 0".
Anyone know why is it?
| The %d format specifier is for arguments the size of integers, therefore the printf function is expecting two arguments both the size of an int. However, you're providing it with one argument that isn't an int, but rather a special object returned by vector<bool> that is convertible to bool.
This is basically causing t... |
7,193,921 | 7,195,392 | Questions about a Segmentation Fault in C++ most likely caused by a custom copy constructor | I'm getting a segmentation fault which I believe is caused by the copy constructor. However, I can't find an example like this one anywhere online. I've read about shallow copy and deep copy but I'm not sure which category this copy would fall under. Anyone know?
MyObject::MyObject{
lots of things including const a... | Wow....
MyObject::MyObject( const MyObject& oCopy)
{
*this = oCopy;//is this deep or shallow?
}
It is neither. It is a call to the assignment operator.
Since you have not finished the construction of the object this is probably ill-advised (though perfectly valid). It is more traditional to define the assignment o... |
7,193,995 | 7,194,110 | Does C++ optimise construction-and-copy into a copy constructor? | Does a C++ compiler automatically convert:
MyObject object2 = object1;
into
MyObject object2( object1 );
?
Or does it treat it like:
MyObject object2;
object2 = object1;
?
| You can try this to see the exact behavior:
#include <iostream>
class MyObject {
public:
MyObject() {
std::cout << "MyObject()" << std::endl;
}
MyObject(const MyObject& other) {
std::cout << "MyObject(const MyObject& other)" << std::endl;
}
MyObject& operator=(const MyObject& other)... |
7,194,346 | 7,194,391 | Using variables defined in an anonymous namespace in another namespace | I have this in a .cpp file:
namespace {
std::string CListName;
}
namespace EXAMPLE_NS {
CListName = "ListName";
...
But Eclipse highlights the assignment as a Syntax Error. I take it you can't use an anonymous namespace from another namespace?
| CListName = "ListName"; is a statement (specifically, it's an assignment expression, which is an expression statement).
A statement cannot appear at namespace scope; you need to put the statement into a function.
|
7,194,420 | 7,194,709 | How to use a .h file during execution without compiling it in C++? | I have to use a header file after the program is compiled. This header is downloaded from a server due to a client petition. Inside the header there are 3 arrays and 1 int that I would like to read during execution.
My first solution is to write a parser. The header files always have the same pattern so I could write 4... | C++ is (usually) a statically compiled language. You compile it, and get some executable code out, which you can run. The two stages, before and after compilation, have nothing to do with each others. At compile-time, you deal with C++ source code only.
And at runtime, you deal with a single compiled program, generated... |
7,194,551 | 7,194,566 | Default Initialization list in Qt Widget | when I make a new class in Qt based on QWidget, I get code that looks like this for the constructor,
Board::Board(QWidget *parent) : QWidget(parent) { }
It looks like the QWidget(parent) is part of an initialization list, but if that was true we'd be setting a variable called QWidget equal to the argument parent, corr... | It's a C++ thing: the constructor of the base class is called.
For more details, see e.g.: Tech-FAQ: Constructors in Derived Class
|
7,194,707 | 7,194,999 | A acm problem. What's wrong in my code? | The text of problem:
Input: The input stream contains a set of integer numbers Ai (0 ≤ Ai ≤ 1018). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
Output: For each number Ai from the last one till the first one you should output its square root. Each... | Warning: when I wrote this, the question was still on the code-review site, so it's written primarily as a code review. The part that applies primarily here on SO (fixing the input problem) is only barely mentioned in passing.
For the moment, I'm going to assume that you've fixed the problem @Jeff Mercado pointed out t... |
7,194,841 | 7,194,969 | C++ Nested Template Class Method Issue | I'm having a problem with the method declaration for a nested class template.
I have something like this:
template <typename T>
class HashTrie
{
template <typename Y>
class Entry
{ // members and methods here
};
template <typename U>
class Node
{ // members and methods here
};
// ... | Say this:
template <typename T>
template <typename U>
std::map<char, typename HashTrie<T>::template Node<U> > HashTrie<T>::Node<U>::foo()
{
}
|
7,195,346 | 7,195,892 | Is it wise to pthead_join() class member-variable thread in the destructor? | I need to make a thread that should run for the duration of the time a class exists. The thread should be destroyed with the class. Would it be wise to code with this general design (join in destructor)? Should I use a detached thread instead possibly?
class A {
public:
A() { pthread_create(m_thread, ..... | If you access data from your class A from within the thread then you must join it in the destructor. A detached thread would otherwise access the class data after it has been destroyed which is simply undefined behavior.
Your thread function must be static or global. But you can pass your class' this pointer as arg par... |
7,195,463 | 7,195,492 | Pointers to object as class member in "modern C++" | So one rule of thumb I've heard with respect to modern C++ style is that one shouldn't need to use new or delete, and one should instead use smart pointers. So how to go about this when I have a class where one of the members is a pointer to another object. By using a smart pointer I can avoid the need to delete, but I... | You use new. There's nothing wrong with using new, it should just be used as rarely as possible.
(delete on the other hand, should almost never be used, since its usage should always be encapsulated in some sort of RAII handle like a smart pointer or a container.)
Note that when using smart pointers, you should alwa... |
7,195,565 | 7,195,585 | How to get difference between elements of two std::set<string>? | So we have set<string> a and set<string> b and we want to get std::set<string> c which would contain items that would represent a - b (meaning what is left from a if we remove from it all items from b, if b contains more than a or items not present in a we want to keep them alike such simple math with numbers: 5-6 = 0... | I think you want std::set_difference() from <algorithm>.
#include <iostream>
#include <algorithm>
#include <set>
#include <string>
#include <iterator>
using namespace std;
set<string> a;
set<string> b;
set<string> result;
int main()
{
a.insert("one");
a.insert("two");
a.insert("three");
b.insert("a... |
7,195,633 | 7,195,787 | How to handle object destruction in error case vs. non-error case | I have a program that is responsible for reading data, formatting it and creating records, and outputting records to files. The important classes for this discussion are:
RecordGenerator - contains the thread that controls the main flow
(get data, format, output)
FileManager - manages the output files. Records are sen... | This is a typical problem when people start using RAII the way it's not meant to be used. Destructors should clean resources and revert whatever they are responsible to. They should not commit changes. Typical exception safe C++ code looks like this:
allocate resource
do something
commit changes
For example:
X& X::op... |
7,195,649 | 8,879,551 | OpenCV Matrix of user-defined type | Is there a way to have a matrix of user-defined type in OpenCV 2.x? Something like :
cv::Mat_<KalmanRGBPixel> backgroundModel;
I know cv::Mat<> is meant for image and mathematic, but I want to hold data in a matrix form. I don't plan to use inverse, transpose, multiplication, etc., it's only to store data. I want it t... | In the OpenCV documentation it is explained how to add custom types to OpenCV matrices. You need to define the corresponding cv::DataType.
https://docs.opencv.org/master/d0/d3a/classcv_1_1DataType.html
The DataType class is basically used to provide a description of such primitive data types without adding any fields ... |
7,195,688 | 7,195,756 | g++ compiling option | What are options for compile .cpp file into .s and .o without linking it.
I used g++ -s -c but it only produced .o file.
g++ -s with create undefined reference to main (because it a class implementation not a main)
| The option to generate asm files is -S, capital S on gcc (you were using -s).
|
7,195,700 | 7,195,720 | Is this c++ inheritance structure possible? | I have not programmed in c++ in a long time and want some simple behavior that no amount of virtual keywords has yet to produce:
class Base {
public:
int both() { return a(); }
};
class Derived : public Base {
protected:
int a();
};
class Problem : public Derived {
};
Problem* p = new Problem();
p.both()... | No. You will have to use a pure virtual a in base.
class Base {
virtual int a() = 0;
int both() {
return a();
}
};
|
7,195,711 | 7,196,274 | C++ Smart pointer own implementation | Let's say that you're on a system where you cant use TR1, boost, etc. You just have the straight-up standard library C++.
If you were stuck with this scenario, what's the simplest reference-counting smart-pointer you could use? (our system only has auto_ptr which is not overly useful).
I'm happy with a link to somethi... | Well some time ago I just made one for studding interest. It's not so "smart" but anyway better then raw pointer.
class CReferenceCount
{
private:
unsigned int m_count;
public:
CReferenceCount() : m_count(0) { }
virtual ~CReferenceCount() { }
void increseRef()
{
++m_count;
}
unsigned int ... |
7,195,776 | 7,195,958 | how to get the first non NULL value in a MAP? | i have an STL map ;
i would like to get the first non NULL value in the map;
is there an efficient/quick way to do that?
| #include <map>
#include <algorithm>
#include <iostream>
using namespace std;
bool IsNotNull(const pair<const int, int>& i)
{
return i.second != 0;
}
int main() {
map<int, int> m;
m[0] = 0;
m[1] = 1;
map<int, int>::const_iterator it = find_if(m.begin(), m.end(), IsNotNull);
... |
7,195,781 | 7,196,502 | How can I add resizable widgets in Qt Creator? | How can I add resizable widgets in Qt Creator?
Specially widgets in QVBoxLayout or QHBoxLayout
| Example:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget* w = new QWidget;
QVBoxLayout* l = new QVBoxLayout;
w->setLayout(l);
QPushButton* b = new QPushButton("hello");
b->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
l->addWidget(b);
w->show(); ... |
7,195,959 | 32,020,990 | Hello world with boost python and python 3.2 | So I'm trying to interface python 3.2 and c++ using boost python, and have come across many many issues. I've finally gotten it to compile using the 2.7 libraries and it works, but I can't seem to make it work with python 3.2.
Here's the c++ code
#include <iostream>
using namespace std;
void say_hello(const char* na... | Although this discussion old, just for the record:
Modify project-config.jam to change the python version to your setup
# Python configuration
using python : 3.4 : /usr ;
Then build boost:
./b2 clean
./b2 --with-python link=static cxxflags="-std=c++11 -fPIC" variant=release stage
./b2 --with-python link=static cxxflag... |
7,196,013 | 7,196,047 | c++, evaluating expressions with multiple `&&`s and no operator of lower precedence | If an expression evaluates multiple && operators, and does not evaluate any operators of lower precedence (eg. ||, ?:), will the expression evaluate to 0 as soon as one of the &&s return 0, or will it finish evaluating the remaining &&s?
For example,
q=0; w=1; e=1; r=1;
if(q && w && r && e) {}
Will this if() evalua... | Yes, evaluation will terminate early ("short circuit") as soon as a false expression is encountered. There is one exception to this: if the && operator has been overloaded for the relevant types of arguments. This is strongly discouraged and extremely rare, but could happen.
|
7,196,094 | 7,196,123 | C++ Static function duplication | Let's say I have a class with a static function. The class's constructor does a pthread_create using the static function as its entry point.
My question is:
If I had multiple instances of this class, would they all run their own thread using that function? Are there any issues with doing this? And... if the function ... | If your constructor does a pthread_create() every time, then you'll have as many threads as you do objects. If those threads access static variables in your class, you will need to ensure that access to those variables is protected by a mutex. (Also, if those threads access non-static variables, you'll want to protect ... |
7,196,172 | 7,196,224 | Can a pointer to base point to an array of derived objects? | I went to a job interview today and was given this interesting question.
Besides the memory leak and the fact there is no virtual dtor, why does this code crash?
#include <iostream>
//besides the obvious mem leak, why does this code crash?
class Shape
{
public:
virtual void draw() const = 0;
};
class Circle : pu... | You cannot index like that. You have allocated an array of Rectangles and stored a pointer to the first in shapes. When you do shapes[1] you're dereferencing (shapes + 1). This will not give you a pointer to the next Rectangle, but a pointer to what would be the next Shape in a presumed array of Shape. Of course, this ... |
7,196,411 | 7,196,708 | Memory leak - release and delete | IFSUPCUTILSize* size = NULL;
CoCreateInstance(CLSID_UTILSize, NULL, CLSCTX_INPROC_SERVER, IID_IFSUPCUTILSize, reinterpret_cast<void**>(&size));
if (size != NULL){
size->Release();
size = NULL;
}
delete size;
Do I need "delete size" in the code above?
If I include "delete size", will I have a memory lea... | COM interfaces are reference counted. CoCreateInstance() returns an interface pointer to a COM object whose reference count has already been incremented. Calling Release() decrements the reference count. When the reference count falls to zero, the COM object frees itself automatically. DO NOT call delete on a COM i... |
7,196,924 | 7,210,943 | Fancy indexing in C++ using boost::range | I'd like to use boost::range to pull off something similar to the "fancy indexing" available in NumPy and Matlab. Specifically, I would like to select certain elements of one indexable container using elements of another container as the indices. For example, one can do the following in Python:
>>> squares = numpy.aran... | OK, so I managed to get something working using boost::permutation_iterator as the basis for the range adaptor. Since permutation_iterator is used, I called the range adaptor "permuted" rather than "sampled" as it is referred to in question's code excerpt. So the C++ version of the numpy code looks like this:
// Step 3... |
7,197,227 | 7,197,375 | Some confusions in C++ Templates | I am right now reading this book , C++ templates : Complete guide. At a para i got stuck couldn't understand the terminology , here is the para:
A fundamental principle is that any template argument must be a
quantity or value that can be determined at compile time. As becomes
clear later, this requirement transla... | There are certain expression in C++ that are required to be known at compile time. For example:
int someArray[30];
The 30 must be a compile-time constant in C++. It could have been:
int someArray[30 + 3];
That is fine, because the compiler has all of the information necessary to compute at compile time how big to mak... |
7,197,589 | 7,197,619 | C++: What is the printf() format spec for "float"? | C++: What is the printf() format spec for float? (Visual C++)
It used to be that I used %g for float and %lg for double.
It looks like the spec changed and float is undefined and double is %g.
I have bits in memory that I am printing out so casting is not an option.
Is there a way that I can print out float values usi... | double and float use the same format specifiers with printf (%a, %e, %f, and %g). This is because printf is a variadic function. Any float arguments are implicitly promoted to double before the call; you can't actually pass a float to printf.
|
7,197,677 | 7,200,917 | Base pointer to array of derived objects | Following a question asked here earlier today and multitudes of similary themed questions, I'm here to ask about this problem from stadard's viewpoint.
struct Base
{
int member;
};
struct Derived : Base
{
int another_member;
};
int main()
{
Base* p = new Derived[10]; // (1)
p[1].member = 42; // (2)
delete[]... | If you look at the expression p[1], p is a Base* (Base is a completely-defined type) and 1 is an int, so according to ISO/IEC 14882:2003 5.2.1 [expr.sub] this expression is valid and identical to *((p)+(1)).
From 5.7 [expr.add] / 5, when an integer is added to a pointer, the result is only well defined when the pointer... |
7,197,811 | 7,197,944 | Problem accessing 4d vector | I have a 4d vector and I am trying to add values to it. I don't receive any compiler errors, but when running it, the program freezes when it gets to the line where I am adding values to this vector.
I initialize the vector in a header file like this:
std::vector<std::vector<std::vector<std::vector<unsigned int> > > > ... | The operator[] does not expand or guarantee that the element is valid. It's a faster version of at() with little or no error checking:
Convert your code to the safer version for now:
_celllist.at(ix).at(iy).at(iz).push_back(i);
This new code will throw an out_of_range exception if your indices are off.
|
7,197,887 | 7,197,971 | Ambiguous base with multiple inheritance | I am trying to write some subclasses of classes in a big library. I am getting an "ambiguous base" error. Here is a compilable example of the problem:
#include <iostream>
// I can't change these because they are in the library:
class InteractorStyle {};
class InteractorStyleCamera : public InteractorStyle {};
class In... | Your problem is that Interactor style is inherited twice - once by PointSelector2D and once by InteractorStyleCamera. This means that you have 2 versions of every member of it contained within your class.
Check out:
How can I avoid the Diamond of Death when using multiple inheritance?
And try virtual inheritance.
|
7,197,972 | 7,198,215 | Get the information about the USB device inserted | I've managed to check if a USB device is inserted through WM_DEVICECHANGE.
case WM_DEVICECHANGE:
{
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
switch(wParam)
{
case DBT_DEVICEARRIVAL:
{
if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
{
// ... | VID and PID are sent with the DBT_DEVTYP_DEVICEINTERFACE message. You can then look in the device drivers for more information via SetupDiGetClassDevs/SetupDiEnumDeviceInfo/SetupDiGetDeviceInstanceId/SetupDiGetDeviceRegistryProperty.
Media is not necessary available at the time of the connection. Think about a card re... |
7,198,081 | 7,198,189 | throwing exception from constructor | Out of my curiosity..
I notice when I throw exceptions from constructor, if I compiled the code in debug mode and if I click on continue debugging (or continue stepping through), it won't exit the constructor until it reaches the end. Please note I don't have try{}catch{} wrapping the code that instantiate MyClass obje... | I suspect that it's a debugging issue. An uncaught exception should, by default, kill the program. But your debugger stops the program at the line that caused the exception, instead. And the "continue debugging" button tells the debugger to just ignore the last fatal problem and continue going.
So the debugger conti... |
7,198,238 | 7,198,255 | Does an inherited function not count as an implementation? | I have a function defined in a superclass, InteractorStyle. Then I have another class that requires that function to be implemented (pure virtual), PointSelector. Then a subclass of PointSelector, PointSelector2D, is instantiated. The compiler complains that I can't instantiate an abstract class because MyFunction() is... | Because with multiple inheritance, you have now inherited two unrelated functions, one from each base class. They just so happen to have the same name as each other (in fact, they don't; one is called InteractorStyle::MyFunction, the other is called PointSelector::MyFunction).
But one does not override the other (at l... |
7,198,312 | 7,198,381 | Does gcc or other compilers auto convert bitwise or's to boolean or's when used in conditional expressions? | If I have a C statement with the logical OR operator || :
if (isFoo() || isBar())
blah();
I know the compiler generated code will not execute isBar() if isFoo() returns true.
What about the bitwise OR operator | ?
if (isFoo() | isBar())
blah();
Likely this is sloppy writing, or if the writer requires isBar() ... | The compiler is free to optimize the "or'ing" however it wants, but the program must behave as if both function calls actually happen, and they could happen in either order. This actually bit me once when I naively changed a || to | because I needed both calls to happen, but forgot that the right-hand call could happen... |
7,198,332 | 7,198,372 | Are find and read operations on std::map threadsafe? |
Possible Duplicate:
Thread safety of std::map for read-only operations
Having std::map a can we do a.find(...)->second in multiple threads at the same time on it?
| Yes. As long as none of your threads do a write
i.e. Construct the data structure in memory
Use as many threads to find/read as you require.
If the leaf needs altering put a mutex there.
|
7,198,509 | 7,301,844 | Connecting mysql in c++ using eclipse? | I'm using Eclipse, and I get errors saying "Unresolved inclusion: mysql_connection.h and similar errors at all the #include statement related to the mysql headers and usage of other keywords related to mysql in the program.
I have installed the complete setup of the mysql server.
so i think its linker error , my questi... | I have never used Eclipse before. However, your little error that says "Unresolved inclusion: mysql_connection.h" suggests that the compiler has no idea where to find your header files. So, I would double check to see if your include paths are correct. To use MySQL Connector/C (I'm assuming that is what you're using...... |
7,198,537 | 7,198,571 | Embed python code in C++ (Windows + minGW + Python 2.7.2 + Eclipse) | I'm trying to embed python code in C++ (Windows 7 + minGW + Python 2.7.2 + Eclipse Indigo with CDT and PyDev).
So, this is the simple code:
#include <Python.h> //Python.h
#include <iostream> //iostream
using namespace std;
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import ... | That is a linker error, not a compiler error. You need to link to the python. As you can see, with the "CrossGCC" toolchain you are almost there:
-lC:/Python27/libs/libpython27.a
You need to change this to
-LC:/Python27/libs -lpython
|
7,198,561 | 7,198,603 | mutable boost::mutex is it possible to separate lock and wait functions? | So I have functions like read that can be called at the same time from multiple threads. but also I have a function to write that needs to lock all that read functions. Where to get example of creating such archetecture?
I get that we can have:
mutable boost::mutex the_read_mutex;
mutable boost::mutex the_write_mutex... | You can use
boost::shared_mutex m
Reader()
shared_lock lock(m)
Writer()
upgradeable_lock lck(m)
upgrade_to_unique_lock uniqueLock(lck);
To know more about boost-locks : Boost thread sync mechanisms
To know about the class of the problem you are dealing with : Wikpedia Link to Reader-WriterLock
To know more ab... |
7,198,745 | 7,198,766 | (Simple?) pointer to non-static member function question | See the code below - I want to know how to, or if it is even possible to, write the body of A::DoThisOrThat()
class A
{
void DoThis( void ) { // any function body you like... }
void DoThat( void ) { // any function body you like... }
void DoThisOrThat( const bool doThis );
};
void A::DoThisOrThat( const bool do... | I might be missing something, but isn't it much easier and simpler to do this?
void A::DoThisOrThat(bool doThis)
{
if(doThis) { DoThis(); }
else { DoThat(); }
}
Assuming you really want to go the function pointer route, realize that pointer to member functions are completely different beasts from point... |
7,198,894 | 7,199,239 | How to use Qt on another project in Visual Studio once it is already working on one project | I am new to C++ and Qt and I am supporting a project using it. Someone set up my Visual C++ environment with Qt. I wanted to start another test project for me to practice with C++ and Qt. Ive created a new C++ project in Visual Studio, but I have no idea how to add the Qt library to it. There is a Qt menu item at the t... | When you select new project in VisualStudio (SHIFT+CTRL+N) you should see Qt4 Projects tab to your left. Select it and then select the type of Qt project you want create. Most likely you would be needing a "QtApplication" or "Qt Console Application" . When you create an application this way, you will have all Qt librar... |
7,198,949 | 7,199,731 | Can't build Boost 64 bit dynamic libraries, only static | I have recently acquired Visual Studio 2010 through Dreamspark, so I can now compile 64 bit applications and libraries. I then compiled the Boost 1.47 libraries with Bjam using the following line for input.
.\b2 -a -d 0 -q -j 4 -d 0 --variant=debug,release --link=shared,static --threading=multi --address-model=32 --to... | The options that change how Boost is compiled (as opposed to those that just control b2's execution) are called "features" and must not be preceeded by dashes on the command line. In your example the features are:
variant
link
threading
address-model
toolset
The libraries it generates will be named according to the
... |
7,199,139 | 7,199,154 | CreateThread() // GetLastError() returns 87 | Below is a simple program that creates a thread. I hope I am missing something obvious. FYI - I am a newb to Win32.
Why does GetLastError() in the thread execution return 87 (ERROR_INVALID_PARAMETER) ?
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
long WINAPI Run();
int _tmain(int argc, _TCHAR* argv[]... | The GetLastError() function only returns valid results when it is called immediately after a Win32 API function that returns a "failed" result.
In your case, you are calling GetLastError() as the first thing in a new thread, which is definitely not immediately after a Win32 API function call.
Also, each thread has its ... |
7,199,241 | 7,199,248 | Reversing a string in C++ using a reverse iterator? | I have the following code and I just can't seem to figure out a way to get the strings reversed here:
stringstream convert;
string y="";
string z="";
convert << x;
string::reverse_iterator rit;
y=convert.str();
int j=0;
for (rit = y.rbegin(); rit < y.rend(); rit++){
z[j] = *rit;
j++;
}
Can someone help me out... | z.assign(y.rbegin(), y.rend());
Or you can do it upon construction:
std::string z(y.rbegin(), y.rend());
If you want to modify a string in place, use std::reverse:
std::reverse(y.begin(), y.end());
|
7,199,502 | 7,199,517 | Char* not retaining text inside my class - initialization constructor problem? | I have the following class (I've trimmed irrelevant stuff):
class Example
{
private:
char* name;
int value[4];
int numVals;
public:
Example();
Example(char name[], int numVals, int, int, int, int);
~Example();
};
And here is the initialization constructor:
Exampl... | You should run your program through a memory debugger to witness the nightmare you've created!
You are using manual memory management in your class, yet you forgot to obey the Rule of Three: You didn't implement the copy constructor, assignment operator and destructor! Thus the temporary does allocate memory, copies th... |
7,199,574 | 7,199,598 | is `std::map<..> a; blah = a[abcd];` thread safe if abcd was not created before this call? | So we created a map. We want to get some_type blah = map_variable[some_not_inserted_yet_value] this would call add new item to map if one was not previosly created. So I wonder if read is really thread safe with std::map or it is only possible to thread safly try{ ...find(..)->second...?
| The idea that calling find(...)->second is thread-safe is very dependent of your view of thread-safety. If you simply mean that it won't crash, then as long as no one is mutating the dictionary at the same time you're reading it, I suppose you're okay.
That said, indeed, no matter what your minimum thread safety requir... |
7,199,809 | 7,199,834 | expected class-name before '{' token | I'm getting the error "expected class-name before '{' token" in my C++ Qt project. After googling it, it seems like its a problem of circular includes. I have pawn.h that includes piece.h, which includes board.h, which completes the circle by including pawn.h. I've read that this can be fixed with forward declarations,... | Instead of randomly trying things, try changing board.h to include forward declarations for all the pieces:
board.h
class Pawn;
class Knight;
class Bishop;
class Queen;
class King;
And remove the corresponding #include statements. (You'll probably need to put those #include statements in board.cpp, when you decide you... |
7,200,029 | 7,200,117 | HWND variable defined in global scope breaks compilation | For some reason when I declare my control in global scope my appication will not compile. When I declare the variable inline everything is fine. The following will not compile:
//Global
HWND hEdit;
...
case WM_CREATE:
{
// Create an edit box
hEdit= CreateWindo... | Argg... I named this file with a .c rather than a .cpp
Not sure why they would result in the problem I was seeing but I noticed I was getting an 'undeclared identifier' error as well. Renaming the file did the trick. I think I'll call it a night :)
Thanks for the comments and replies.
|
7,200,137 | 7,200,388 | Appending text to a Win32 EditBox in C++ | I have an EditBox HWND tbLog, and the following function (which doesn't work):
void appendLogText(char* newText)
{
int len = GetWindowTextLength(tbLog);
char* logText = new char[len + strlen(newText) + 1];
GetWindowText(tbLog, logText, len);
strcat(logText, newText);
SendMessage(tbLog, WM_SETTEXT, NULL, (L... | I would rewrite the function, in C, like this:
void appendLogText(LPCTSTR newText)
{
DWORD l,r;
SendMessage(tbLog, EM_GETSEL,(WPARAM)&l,(LPARAM)&r);
SendMessage(tbLog, EM_SETSEL, -1, -1);
SendMessage(tbLog, EM_REPLACESEL, 0, (LPARAM)newText);
SendMessage(tbLog, EM_SETSEL,l,r);
}
Its important to save and res... |
7,200,154 | 7,200,185 | Is casting a base pointer to a derived pointer dangerous in any way? | I have always avoided the C++ casts (static_cast, const_cast, dynamic_cast [I also avoid RTTI], etc) because I regard them as a waste of typing and I never saw any advantages, so I use C-style casts exclusively.
My question is, if you have an inheritance hierarchy and a pointer to the base type, can you safely cast a b... | Using static_cast or dynamic_cast for casting ensures some kind of safety.
static_cast gives you an compile time error if an cast is invalid while,
dynamic_cast throws an exception for References or returns a null pointer in case of invalid cast at run time.
Thus they are better than the c-style cast mainly due the s... |
7,200,446 | 7,200,809 | Does downcasting defeat the purpose of polymorphism? | I encountered a question today, found here, which raised this question for me.
Here's a pseudo-code example of what I'm getting at:
class Car{
public:
virtual int goFast() = 0;
};
class FordFocus : public Car {
public:
int goFast(){
return 35;
};
};
class Lamborghini : public Car {
bool roof... | Now if there are more than one type of cars which is retractable, say such cars are CarA, CarB, and CarC (in addition to Lamborghini), then are you going to write this:
if(Lamborghini* lambo = dynamic_cast<Lamborghini*>(cars[i])) {
lambo->retractTheRoof();
}
else if(CarA * pCarA = dynamic_cast<CarA*>(cars[i])) {
... |
7,200,674 | 7,200,762 | Is NULL defined as nullptr in C++11? | Will C++11 implementations define NULLas nullptr?
Would this be prescribed by the new C++ standard?
| From the horse's mouth
C.3.2.4 Macro NULL [diff.null]
1/ The macro NULL, defined in any of <clocale>, <cstddef>, <cstdio>, <cstdlib>, <cstring>, <ctime>, or <cwchar>, is an implementation-defined C++ null pointer constant in this International Standard (18.2).
It is up to each implementation to provide its own defini... |
7,200,852 | 7,201,009 | Syntactic sugar to add variable-size element lists to vector? | I have a class that contains a vector:
class Foo {
typdef std::vector<int> Vec;
Vec m_kids;
void addKids(Vec::const_iterator begin,
Vec::const_iterator end) {
m_kids.insert(m_kids.end(), begin, end);
}
};
Is there any way to allow the following concise function calls? (Maybe by changing the... | You can do this:
Foo foo;
foo << 3, 6, 1, 4, 88, 2, 4, -2, 101; //inserts all!
For that you've to overloaded << and , operators, as:
class Foo {
typdef std::vector<int> Vec;
Vec m_kids;
public:
Foo& operator<<(int item) {
m_kids.push_back(item); return *this;
}
Foo& operator,(int item) {
m_kids.push_... |
7,201,378 | 7,201,613 | Using UpdateResource() to update one's own resources | I have an application whose resources need to be updated externally from time to time. I want the application to update it's own resources.
The problem with UpdateResource() is that it cannot be used on a currently executing process. Any ideas how I can update resources from the application itself instead of writing a... | This seems to be not a good solution to update the application resources. Programs are installed with Administrator rights. A standard user has no write access to the program executable files. Consider saving the data you need in a user directory. E.g. %LOCALAPPDATA%. If you really need resources you can also put a res... |
7,201,494 | 7,201,552 | valgrinf error- how to interpretate it? | I have the following error when using valgrind:
==3099== Conditional jump or move depends on uninitialised value(s)
==3099== at 0x40BA65D: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_int<long>(std::ostreambuf_iterator... | This error means that you are working with some variables before they were initialized. Looks like you are printing uninitialized int value in Ser::method(). You should initialize it before printing.
|
7,201,499 | 7,202,596 | Differences between Xerces-C++ v2 and v3 branches | Checking the Xerces-C++ webpage, I saw there are two major branches of the parser:
Version 2.8.0 and Version 3.1.1
What are the main differences between those two? (couldn't find any summary on their page)
Which one should I choose for starting a brand new Visual Studio
2010 C++ project?
Thanks for any help
|
already answered by PlasmaHH with migrate to v3
There are pre-built binary distributions and ready-made project files for Visual Studio 2010 available only for Xerces-C++ v3.
Xerces-C++ v2 supports Visual Studio up to version 2005.
Therefore I suggest to go with Xerces-C++ v3.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.