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 |
|---|---|---|---|---|
6,241,271 | 6,241,321 | Parallel Sum for Vectors | Could someone please provide some suggestions on how I can decrease the following for loop's runtime through multithreading? Suppose I also have two vectors called 'a' and 'b'.
for (int j = 0; j < 8000; j++){
// Perform an operation and store in the vector 'a'
// Add 'a' to 'b' coefficient wise
}
This for loop... | omp creates threads for your program whereever you insert pragma tag, so it's createing threads for inner tags but the problem is 16 threads are created, each one does 1 operation and then all of them are destroyed using your method. creating and destroying threads take a lot of time so the method you used increases th... |
6,241,350 | 6,243,951 | Still having race condition with boost::mutex | I am trying an example, which causes race condition to apply the mutex. However, even with the mutex, it still happens. What's wrong? Here is my code:
#include <iostream>
#include <boost/thread.hpp>
#include <vector>
using namespace std;
class Soldier
{
private:
boost::thread m_Thread;
public:
static int count , mo... | Based on this and your previous post (were it does not seem you have read all the answers yet). What you are looking for is some form of synchronization point to prevent the main() thread from exiting the application (because when the main thread exits the application all the children thread die).
This is why you call ... |
6,241,660 | 6,241,750 | Qt, widget refresh, and ui interactability | I'm sparkling brand new to Qt, and am finding it very rewarding to learn. I'm trying to merge some existing C++ code with a new Qt GUI. Basically, the idea is to have images that are extracted from an .avi file be processed in the backend and then displayed in a QLabel on-screen. I have managed to get the following bit... | You should really have a look at the Qt Phonon multimedia framework. Might not get you the level of control you have with OpenCV over the media files, but it's worth a good looking into.
For your original question: you have to do the processing in a different thread. This gets tricky because you can only call GUI funct... |
6,241,672 | 6,241,700 | Multiple if statements in C++ | I'm doing the first project euler problem and I just did this
#include <iostream>
using namespace std;
int main(){
int threes =0;
int fives = 0;
int both = 0;
for (int i = 0; i < 10; i++){
if(i%3==0){
threes += i;
}
if(i%5==0){
fives += i;
}
if ( i % 5 == 0 && i % 3 == 0)... | The else branch in an if-else statement is only executed if the if branch is false. If you just have two if statements in a row, they'll both be executed, which can be a waste. In the below code, the else prevents the second computation from running if the first is satisfied.
if (expensive_computation1()) {
...
}
els... |
6,241,689 | 6,241,715 | curious exception in Visual C++ 10 at runtime | Today I got really strange exception at runtime. I tried to debug step by step, but the exception occurs before main() is called.
So I removed every include and the whole code (commented it), and added an empty main() function.
And again, after compiling it occurs. Maybe a project configuration bug?
BTW: after the exce... | The problem is most likely part of the initialization of a global or static object which then calls strlen with a null pointer. Do you have any globals in any .cpp? Or any statics in some classes?
Note that, even if you remove everything from the main.cpp, the other .cpp files will still be compiled and cause the error... |
6,241,738 | 6,241,801 | What exactly is join() in Boost::thread? (C++) | In Java, I would do something like:
Thread t = new MyThread();
t.start();
I start thread by calling start() method. So later I can do something like:
for (int i = 0; i < limit; ++i)
{
Thread t = new MyThread();
t.start();
}
To create a group of threads and execute the code in run() method.
However, in C++, t... | join doesn't start the thread, it blocks you until the thread you're joining finishes. You use it when you need to wait for the thread you started to finish its run (for example - if it computes something and you need the result).
What starts the thread is boost::thread, which creates the thread and calls the thread fu... |
6,241,939 | 6,241,988 | Does an extension exist for Visual Studio which allows quick switching between different development roles? | I'm generally a C++ guy, but I've got to switch to C# some of the time in order to build things for the "Windows Phone" platform. Or when I have to go to work. Whatever. Point is, I work very differently when I'm in C++ than when I'm in C#.
I'd like to have a quick and fast way of switching between these two. I know th... | Not exactly an extension, but take a look at this blog post by Sara Ford: Did you know… You can create toolbar buttons to quickly toggle your favorite VS Settings?
|
6,241,971 | 6,241,990 | Improper typecasting in Class constructor | I'm new to C++ and I have a problem with classes.
I got this prototype
class MMA7455 : public Accel
{
public:
MMA7455(uint8_t);
uint8_t accel_get_data(acceleration_t*);
private:
uint8_t accel_data_ready(void);
};
and I want to create an instance of it
MMA7455 accel = MMA7455(0x21);
but the following messa... | You probably didn't link your .cpp file containing the constructor definition. "uint8_t" is a typedef for 'unsigned char".
|
6,242,006 | 6,242,030 | struct member alignment - is it possible to assume no padding | Imagine a struct made up of 32-bit, 16-bit, and 8-bit member values. Where the ordering of member values is such that each member is on it's natural boundary.
struct Foo
{
uint32_t a;
uint16_t b;
uint8_t c;
uint8_t d;
uint32_t e;
};
Member alignment and padding rules are documented for Visual C++. ... | On systems that actually offer those types, it is highly likely to work. On, say, a 36-bit system those types would not be available in the first place.
GCC provides an attribute
__attribute__ ((packed))
With similar effect.
|
6,242,296 | 6,242,355 | Conversion function for error checking considered good? | I'd like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this:
operator bool() const { return is_valid; }
Checking for it to be valid would be very simple now
// is my object invalid?
if (!my_object) std::cerr << "my_object isn't valid" << std::end... | In C++03, you need to use the safe bool idiom to avoid evil things:
int x = my_object; // this works
In C++11 you can use an explicit conversion:
explicit operator bool() const
{
// verify if valid
return is_valid;
}
This way you need to be explicit about the conversion to bool, so you can no longer do crazy ... |
6,242,317 | 6,242,386 | C++ API writes Varint in different fashion to file than to socket | I want to ask because I find that strange: the way varint is written is depend on the target.
My simple code can write to a file or to a socket. When I write to the file the hexdump shows
0000000 02ac
0000002
When I write to the socket the C# client that reads byte by byte shows
ac 02
the code resposible for tha... | I'm guessing you're using hexdump (or od) to show the file contents, and that you don't actually have a problem ;-)
Demo:
$ echo -n ab > file
$ hexdump file
0000000 6261 # notice this is 'ba'
0000002
$ hexdump -C file
00000000 61 62 |ab|
00000002
Without options, h... |
6,242,364 | 6,242,617 | vector optimization - simple method | i have a doubt on following case;
suppose i want to define a vector of vector to acomadate set of elements and i can add the data and can be used those elemnts to compute something else. then i dont want that vector anymore. then later, suppose if i want to accomadae another set of data as a vector of vector, then i ca... | If this is homework (or not) and you want to know which is faster then you should try it: run the "push back and clear" or "new and delete" in a loop a few million times and time the execution. I suspect 2. will be a bit faster.
You say you want to accommodate a set of elements, and that the size of the inner vector is... |
6,242,387 | 6,244,414 | Boost libraries for UTF-16 strings? | Are there any boost libraries to help with UTF-16 (or higher) strings?
| There's nothing officially in Boost yet, but Boost.Unicode is actively in development.
|
6,242,448 | 6,242,528 | Make main() "uncrashable" | I want to program a daemon-manager that takes care that all daemons are running, like so (simplified pseudocode):
void watchMe(filename)
{
while (true)
{
system(filename); //freezes as long as filename runs
//oh, filename must be crashed. Nevermind, will be restarted
}
}
... | This seems more like a SEH exception than a C++ exception, and needs to be handled differently, try the following code:
__try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARC... |
6,242,658 | 6,242,711 | Random Numbers in C++ | I'm creating a BlackJack Program. I want the cards to be randomly dealt. if i use the rand() function and initialize srand() to time(NULL) then all the cards turn out to be same. Any idea what the problem might be ?
//Cards.h
#include <iostream>
#include <time.h>
#include <cstdlib>
using namespace std;
class Cards
{
... | Seed the number generator ONCE. If you run your function in a loop they will be executed faster than the time resolution interval (so all the seeds are the same and therefore the numbers).
While developing the app and debugging it it will help if you seed the generator with the same, known value. This means successive ... |
6,242,768 | 6,242,777 | Is the safe-bool idiom obsolete in C++11? | This answer of @R. Martinho Fernandes shows, that the safe-bool idiom is apperently deprecated in C++11, as it can be replaced by a simple
explicit operator bool() const;
according to the standard quote in the answer §4 [conv] p3:
An expression e can be implicitly converted to a type T if and only if the declaration ... | Yes. This is the example for problems with only having implicit user-defined conversions and explicit user-defined conversion operators were practically invented because of this problem and to replace all the safe-bool stuff with something a lot cleaner and more logical.
|
6,242,790 | 6,242,847 | Add text to QTextEdit using QPushButton | Just a simple program to add text to textedit when button is clicked...
anything wrong here??
#include<QPushButton>
#include<QApplication>
#include<QTextEdit>
#include<QWidget>
#include<QHBoxLayout>
#include<QLabel>
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QHBoxLayout *layout=new QHB... | You can't use connect like that. You cannot pass parameters to the SLOT that are not present in the connected SIGNAL.
You will need to connect the clicked() signal to your own slot (with no argument), and call the setPlainText function yourself (or emit a new signal that has a QString parameter).
The other option is to... |
6,242,849 | 6,242,862 | anyway to delete only part of array? | char myWord[20];
I want to delete last 10 chars of this array, I mean freeing the memory thats being used by last 10 chars. Is there anyway to do this ?
Heres an example function for substring where it might be useful.
str& substring(uint Start, uint Count){
for(uint x=0; x<Count; x++){
mString[x] = mStrin... | No, not really. You can really only do it if you obtained a pointer to memory from malloc, and then used realloc to change the size, but I'm quite sure that it's not even guaranteed that it will free the unused bytes.
|
6,243,041 | 6,243,097 | static member variable file scope | Static variable has the scope inside that file only where they are been declared, as shown in below code:
file1-
static int a;
file2-
extern int a;
This will give linking error as static variable a has the scope in file1 only. But I am confused with below code:
file2-
#include "file1"
extern int a;
Here it would no... | file1:
static int a;
file2:
extern int a;
There are two variables referenced here. The first is a declaration and definition of a variable with internal linkage in file1; the second is a declaration only of a variable with external linkage in file2. This doesn't necessarily cause an error; it is completely legal to h... |
6,243,092 | 6,243,139 | C/C++. Advantages of libraries over combined object files | While it is commonplace to combine multiple object files in a library, it is possible (at least in Linux) to combine multiple object files into another object file.
(See combine two GCC compiled .o object files into a third .o file)
As there are downsides to using libraries instead of just combined object files:
1: It'... | While it depends on the linker being used, object files are being included in the final binary in their entirety. So, if you combine several object files into one object file, then the resulting (combined) object file is included in the resultant binary.
In contrast, a library is just that, a library of object files. T... |
6,243,145 | 6,243,217 | stl container for table | Is there any data structure for a table? like storing this:
Width Height
1 5 10
2 3 20
3 10 2
What I need is to address a value by row number and title, e.g. (2, "Height") will give 20.
I know I can do an array of maps or 2d array and a map as column name to number, but is there ... | Have you looked at Boost::MultiIndex yet? It's almost like an in-memory representation of a database table. You can query on several rows, a single row, and such. Very powerful, very useful, and I think it would solve the issue you're asking.
Taken from the boost website:
Boost.MultiIndex features additional functi... |
6,243,254 | 6,243,295 | Naming of hierarchical structures in C++ | I need advice for the following hierarchical structure, I want to represent in a C++ program.
There is one abstract class uri and the classes url and urn which derive from it.
I would like to have one directory containing the source code of the uri concept. And a namespace which should be called .. uri. :)
So, I'm comi... | Namespaces are not based nor should they be based on the actual directories that hold the files.
Their purpose is to group related classes/structs/constants together and reduce ambiguities.
There is no problem with naming a class the same as its containing namespace (such as uri::uri). Names should be chosen with the p... |
6,243,362 | 6,243,556 | how to use extensions from protocol buffers to maintain 'general' message | My client-server communication looks like this: there are some so called annoucements which are seperate messages used to exchange information. The idea is that annoucement is the common part of every message. Actually I suppose it will be the type of the message. The type decide what is the content. In UML class diagr... | There are a number of ways you could do this. I'm not actually sure extensions is the one I would leap for, but:
in your message type, you could have a set of fully defined fields for each sub-message, i.e.
base-message
{1-5} common fields
{optional 20} sub-message 1
{optional 21} sub-message 2
{optional 22} su... |
6,243,381 | 6,243,418 | Is it advisable to declare pointer to heap memory as `const` ALWAYS? | T *p = new T();
For the pointer on heap, there can be disastrous operations such as,
p++; // (1) scope missed
p = new T(); // (2) re-assignment
Which would result in memory leaks or crashes due to wrong delete. Apart from using smart pointers, is it advisable always to make heap pointer a const;
T* const p = new T()... | I hesitate to say always, but what you propose seems reasonable for many/most cases. Const correctness is something most C++ folks pay a fair bit of attention to in function parameters, but not so much in local (or even member) variables. We might be better off to do so.
|
6,243,385 | 6,243,880 | C++ performance weirdness w/ OpenGL | I am rewriting some rendering C code in C++. The old C code basically computes everything it needs and renders it at each frame. The new C++ code instead pre-computes what it needs and stores that as a linked list.
Now, actual rendering operations are translations, colour changes and calls to GL lists.
While executing ... | By spending time in printf, you may be avoiding stalls in your next OpenGL call.
|
6,243,396 | 6,243,589 | Expression: _BLOCK_TYPE_ISVAILD(pHead->nBlockUse) | void Connection::Receive(){
socket_.async_read_some(boost::asio::buffer(read_buffer_),
boost::bind(&Connection::handle_Receive, shared_from_this(),boost::asio::placeholders::error));
}
void Connection::handle_Receive(const boost::system::error_code& error)
{
if(!error)
{
if(read_buffer_.size() ... | You are getting a double delete from casting a uint8_t* that is owned by a boost::array<uint8_t,1000> to a std::shared_ptr.
ByteBuffer b((std::shared_ptr<uint8_t>)read_buffer_.data(), read_buffer_.size());
^^^^^
Don't do that, a shared_ptr is for pointers with dynamic stora... |
6,243,487 | 6,243,506 | Initialisation lists in constructors trying to initialize a structure | g++ (GCC) 4.6.0
I have the following class and I am trying to initialize in my initialization list of my constructor.
class Floor_plan
{
private:
unsigned int width;
unsigned int height;
struct floor_size {
unsigned int x;
unsigned int y;
} floor;
public:
Floor_plan() : width(0), ... | See default init value for struct member of a class
Either you initialize it inside the constructor
Floor_plan() : width(0), height(0), floor() {
floor.x = 1;
floor.y = 2;
}
Or you create a constructor for the struct, and use that in the initialization list.
struct floor_size {
unsigned int x;
unsigned int... |
6,243,638 | 6,286,504 | Adding static libcurl to Code::Blocks IDE | I can't figure out how to properly add a static libcurl library to my Code::Blocks IDE. I want it static because then no .dll files, which are not included in Windows by default, are needed during runtime of my program. I am using this libcurl:
http://curl.haxx.se/dlwiz/?type=lib&os=Win32&flav=- (minGW without OpenSSL)... | Okay, I managed to build your example successfully with libcurl using static linkage. The details involved to make this work are quite intricate -- setting it up correctly can get tricky for the unwary.
Here are the steps I used to make this work, be sure to follow them carefully:
Go to Project build options->Compile... |
6,243,664 | 6,243,725 | Variadic Templates and Type Traits | I currently have a variadic function which takes an arbitrary number of arguments of arbitrary types (duh), however, I want to restrict the types to ones which are POD only, and also the same size or smaller than that of a void*.
The void* check was easy, I just did this:
static_assert(sizeof...(Args) <= sizeof(PVOID),... | You can write a meta-function to determine if all are POD types:
template <typename... Ts>
struct all_pod;
template <typename Head, typename... Tail>
struct all_pod<Head, Tail...>
{
static const bool value = std::is_pod<Head>::value && all_pod<Tail...>::value;
};
template <typename T>
struct all_pod<T>
{
stat... |
6,243,856 | 6,245,025 | multi-threaded chess using winsock | I've been working on a small network based chess application. I managed to create a server that can handle multiple connections, however I don't know how to send data from one client to another.
Here is the partial Server implementation
//function to handle our Socket on its own thread.
//param- SOCKET* that is connect... | Maybe you should start a thread for a new game when both players of the game are connected to the server. In that case you can deliver both sockets to the thread by the following way:
DWORD WINAPI HandleGame(void* param)
{
GameState* game = (GameState*)param;
SOCKET s1 = game->getSocketOfPlayer(1);
SOCKET s... |
6,243,903 | 6,243,923 | how to convert std::string to QString | I have a problem:
std::string str("character/test/raw");
qDebug() << QString::fromStdString(str);
and the output is:
"]AIIIIIIIIIIIIIIIIIIIIIIIIIIIII"
I think the problem is in encoding but don't know how to fix it. Please help
| Is your QT compiled with STL compatible enabled option?
Maybe you can use fromUtf8 or one of other static functions of QString.
|
6,244,272 | 6,245,589 | Drawing sections of a Bezier curve | I was writing code to approximate a quarter ellipse to a Bézier curve.
Now having done that, I am encountering trouble drawing sections of this curve.
I need some help choosing the control points.
Initially, I had taken the ratio of distance of control point to distance of start of curve as 0.51.
Edited:
pseudo code
... | To approximate a circle quarter using a single cubic arc what is normally done is making the middle point being exactly on the circle and using tangent starting and ending directions.
This is not formally the "best" approximation in any reasonable metric but is very easy to compute... for example the magic number for a... |
6,244,336 | 18,934,601 | Find nucleus involved in nCapture process in Geant4 | I'm trying to determine the target nucleus in an (n,gamma) reaction in Geant4. I have been unable to extract this information. The only place I have found it to be stored is in G4IsoParticleChange which is created by the G4HadronicProcess if Isotope Counting is enabled.
Unfortunately this information is lost (not in a ... | I finally found an effective solution to that problem: I search for a nucleus in the secondary track vector of a step ending by a neutron capture. This nucleus is the one which captured the neutron and which recoil is tracked by Geant4. Do not forget to subtract 1 neutron to this nucleus to get what you want (for a cap... |
6,244,420 | 6,244,437 | "unresolved overloaded function type" when calling templated function from boost::thread | I'm attempting to implement quicksort in-place, using boost's threading facility. Unfortunately I'm getting an error about "", when my function is not overloaded. Code follows:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/thread.hpp>
template<typename T>
void quicksortIn... | It needs to be quicksortInPlace<T>.
|
6,244,431 | 6,244,446 | Can someone explain this C++ syntax? | I'm going through someone else's code and came across the following syntax:
typedef struct abc {
abc() : member(0){}
unsigned int member
}
It seems like a class with member variable and a constructor, except it is declared struct. I have two questions here.
Is this syntax supported in C?
What would be a reas... | This is not valid C.
In C++, struct and class are essentially synonyms. The only difference is that members and inheritance are public by default in a struct, and private by default in a class.
There are no hard guidelines on whether to choose struct or class. However, you'll often find people using struct only for s... |
6,244,718 | 6,244,737 | MS Detours 2.1 - Unresolved externals | I'm using MS Detours 2.1 Library and VS 2010. I'm trying to detour PlaySoundW function.
I can't compile that code and I'm getting these errors:
Error 2 error LNK1120: 1 unresolved externals (...)\detoursLearning.dll detoursLearning
Error 1 error LNK2001: unresolved external symbol __imp__PlaySoundW@12 (...)\... | You're not linking to winmm.lib.
http://msdn.microsoft.com/en-us/library/dd743680%28VS.85%29.aspx
Martyn
|
6,244,931 | 6,244,950 | reference front and pop_front | Is this legal?:
Sample& sample = stack.front();
stack.pop_front();
My program works. But Sample class have boost::optional<boost::posix_time::ptime> xxx member and after pop_front, is_initialized() returns false;
| No, this is not legal. You must take a copy of the object, i.e. use
Sample sample = stack.front ()
If you are using a std::vector, the pop_front call moves the elements behind to the location and your reference points to a different element (the previously second, now first element.)
|
6,245,047 | 6,245,148 | c++ bitset problem with output | I was working around with bitset, and so i was wondering what would be the best way to convert a base-10 to base-2, because for some reason i get the wrong answer:
giving the number 19, i'd expect to see:
10011 (16-2-1), why does it output (00011)
#include <iostream>
#include <bitset>
using namespace std;
int main() ... | There were a bug in your code. You can't access element at index 4 since the size of bitset was 4 due to the fact that sizeof( int ) yielded 4, which only allows accessing from 0-3. As for your question, the template argument within the <> brackets is the size of bitset. In your case, 19 is represented with more than 4... |
6,245,159 | 6,245,192 | operator+= yields zero | [edit]Problem solved - kind of. There never really was a problem. It seems that the debugger was lying to me. Thanks[/edit]
I have a wierd problem that I've been unable to resolve so far. I have a private class member
private:
float *_histVals;
which is initialized in the constructor as follows:
// allocate memory for... | Use std::vector<float> unless you want a difficult life or you're learning how people had to live in the bad old days.
Regarding this having no effect on the array element:
this->_histVals[ hIndex ] += imgFrac;
Possible causes:
The debugger is lying to you.
imgFrac is zero
Have you tried logging all the values invol... |
6,245,235 | 6,249,287 | Confusion about Copy-On-Write and shared_ptr | I have searched the web and read through the Boost documentation about shared_ptr. There is a response on SO that says that shared_ptr for Copy-On-Write (COW) sucks and that TR! has removed it from the string libraries. Most advice on SO says to use shared_ptr rather than regular pointers.
The documentation also ta... | There are several questions bundled into one here, so bear with me if I don't address them in the order you would expect.
Most advice on SO says to use shared_ptr rather than regular pointers.
Yes and No. A number of users of SO, unfortunately, recommend shared_ptr as if it were a silver bullet to solve all memory m... |
6,245,295 | 6,245,408 | Destructor parameters | The article Are destructors overloadable? talks about overloading the destructor.
This raised a question: Can a destructor have parameters?
I've never used or seen a destructor with parameters. I could not come up with an example of a reason to use parameters to the destructor.
| Section §12.4 of C++0x draft n3290 has this to say about destructors:
Destructors
A special declarator syntax using an optional function-specifier (7.1.2) followed by ˜ followed by the destructor’s class name followed by an empty parameter list is used to declare the destructor in a class definition.
(emphasis added)
S... |
6,245,578 | 6,245,684 | Bitwise, bitmasking: whats wrong here? | I wanted to track some options via bitmask'ing them, and borrowed bitmask values from this answer, yet they not seem to work together.
#include <iostream>
#define OP1 0x00003FFFUL
#define OP2 0x00007FFFUL
#define OP3 0x0000FFFFUL
int main() {
unsigned long params = 0; // .
params |= OP3;
if ( ... | For options you should use other masks, ones that are not overlapped, such as:
#define OP1 0x000000FUL
#define OP2 0x00000F0UL
#define OP3 0x0000F00UL
or (in this case you'll be able to store as many options as available bits):
#define OP1 0x0000001UL
#define OP2 0x0000002UL
#define OP3 0x0000004UL
... |
6,245,639 | 6,246,002 | MS Detours 2.1 - Popping out of stack | I wont to detour PlaySoundW function inside Minesweeper.
Game is crashing as soon as it calls PlaySoundW function.
If I uncomment Beep inside my code, game beeps and than crashes.
Now code is calling original function from hooked function so it should't do anything. But it is crashing anyway.
Can you tell me what is wr... | Try setting the calling convention of HookPlaySoundW to __stdcall (because the CC of PlaySoundW is also __stdcall (from Windows.h): WINMMAPI BOOL WINAPI PlaySoundW( __in_opt LPCWSTR pszSound, __in_opt HMODULE hmod, __in DWORD fdwSound);).
I have worked with detours before and after a casual glance everything looks corr... |
6,245,669 | 6,245,683 | What is the default protection level when inheriting a subclass? |
Possible Duplicate:
Default class inheritance access
I know I can set the protection level when I declare a subclass from a superclass as in:
class Dog : public Pet {
*blah, blah, blah*
}
But what does the protection level default to in this case?
Class Dog: Pet {
*blah, blah, blah*
}
| For a class it is private
class Dog: Pet // Pet is inherited privately.
{}
For a struct it is public.
struct Dog: Pet // Pet is inherited publicly.
{}
Simple test:
class Pet {};
class DogClass: Pet {};
struct DogStruct: Pet {};
int main()
{
DogClass dogClass;
// Pet& pet1 = dogClass; This line wi... |
6,245,735 | 6,245,777 | Pretty-print std::tuple | This is a follow-up to my previous question on pretty-printing STL containers, for which we managed to develop a very elegant and fully general solution.
In this next step, I would like to include pretty-printing for std::tuple<Args...>, using variadic templates (so this is strictly C++11). For std::pair<S,T>, I simpl... | Yay, indices~
namespace aux{
template<std::size_t...> struct seq{};
template<std::size_t N, std::size_t... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<std::size_t... Is>
struct gen_seq<0, Is...> : seq<Is...>{};
template<class Ch, class Tr, class Tuple, std::size_t... Is>
void print_tuple(std::basic_ost... |
6,246,094 | 6,246,109 | can I compare two fractions if both have denominator with power of 2 | I know it's not "possible" to compare two real, but is it true for real which have denominator power of 2
Is equality of this king always return true
if( 3/4. == 6/8. ) {}
| This kind of expression should always evaluate to true, with a few caveats:
The numerators don't exceed 2^52; otherwise they'll lose precision.
The denominators don't exceed the range provided by double-precision.
You must be working on a platform that uses radix-2 floating-point (which is basically all modern machine... |
6,246,106 | 6,246,196 | Advantages/Disadvantages of a Inheritance, composition and multiple member variables | I am looking at Ogre3D code and WildMagic code and I found that both deal with their core classes a bit differently. Since I am creating my own core, I was wondering which would be better practice and could potentially be better in terms of resources.
In WildMagic, there is a Matrix class which inherits from a Table cl... | Very good, complicated questions with many, many answers. I'll try to address them as best I can, but at least in my opinion the overall answer is going to do more with what your needs are than what a single individual might do.
1) There is always a cost to inheritance, though it is very minute. There really isn't an... |
6,246,117 | 6,246,190 | C++, point and line position in 2D robust to rounding errors and position | A line is defined by two end points P1[x1, y1], P2[x2, y2]. Let Q [xq, yq] be a tested point. Both coordinates are double.
Differencies:
dx1 = x2 - x1
dy1 = y2 - y1
dx2 = xq - x1
dy2 = yq - y1
Norms
double n1_sq = sqrt(dx1 * dx1 + dy1 * dy1);
double n2_sq = sqrt(dx2 * dx2 + dy2 * dy2);
My assumption: test with normal... | I don't understand your test. It doesn't seem to involve the coordinates of Q at all. Also, for two values u and v, the norm is computed with minimum rounding as M * sqrt(1 + m / M), where M = max(|u|, |v|) and m = min(|u|, |v|). As for a dist function, that is the best approach, although you might want to make the thr... |
6,246,158 | 6,246,860 | 100% CPU usage when overriding QGraphicsLineItem::paint() | I have a class inheriting from QGraphicsLineItem and as soon as I override the paint method, it looks like Qt starts painting it at every "main loop", instead of drawing according to some events (like moving the item, etc).
Does anyone know more about the good practices when inheriting from a QGraphicsItem ? I look at ... | You probably shouldn't call methods like setPos, setRect, setPolygon or update inside your paint() method. These methods are likely to schedule a new paint event which will lead to infinite recursion.
|
6,246,324 | 6,246,351 | Is there a type-trait to remove top-level cv and reference at once? | I just want to know if there is already one provided by the standard. I know it's easy to make one yourself
// for C++03, use <tr1/type_traits> and std::tr1
#include <type_traits>
template<class T>
struct remove_toplevel{
typedef typename std::remove_reference<T>::type noref_T;
typedef typename std::remove_cv<nore... | std::decay, I believe, performs this functionality.
|
6,246,344 | 6,246,377 | std::transform behavior when iterating past container.end() | Code:
static int counter = 0;
int add(int x) {
counter++;
return ++x;
}
int main() {
vector<int> b;
b.push_back(1);
b.push_back(1);
b.push_back(1);
transform(b.begin(),b.end(),b.begin()+2,add);
for (vector<int>::iterator it = b.begin(); it != b.end(); it++)
cout << (*it) << e... | Yes, it's undefined behavior. It's your responsibility to avoid running past the end of the vector, not the compiler's.
What do you mean by, "b.end() is not overwritten"? If you mean that you expected the vector to change length, then no, it didn't, you can't change a vector's length this way.
|
6,246,365 | 6,258,431 | Base class holding a reference to Derived | I'd like to do this:
struct Derived;
struct Base{
Derived const& m_ref;
Base(Derived const& ref) : m_ref(ref){}
};
struct Derived: Base{
Derived(): Base(*this){}
};
But I seem to get unreliable behaviour (when used later on, m_ref points to things that aren't valid Derived).
Is it permissible to construc... | 3.8/1 says:
The lifetime of an object of type T
begins when: — storage with the proper
alignment and size for type T is
obtained, and — if T is a class type
with a non-trivial constructor (12.1),
the constructor call has completed.
3.8/5 says:
Before the lifetime of an object has started but after the stor... |
6,246,619 | 6,246,646 | a fast algorithm to compute matrix multiplication | In the middle of a c++ code, eclipse, I need to compute the multiply of matrices A and B, with the size of 2400*3600 (so the dimensions are not the same). The matrices are stored in float two dimensional arrays.They are not sparse, no limitations.
Each multiply takes so long (several minutes), and I seriously need to r... | I wouldn't fool around trying to write my own: Google for LAPACK or BLAS, two time-tested packages for numerical computing, both optimized to the Nth degree. Both have C APIs you can use.
|
6,246,632 | 6,246,652 | how to compile to reduce memory /STACK doesn't seem to change anything? | I create a lot of simple programs, which don't need any memory, but they always show around 1MB-1.6MB memory in the private memory column in task manager.
I read that the default stack size is 1MB for linking with link.exe, i tried playing with /STACK like this :
/STACK:65536 (64kb)
/STACK:16777216 (16mb)
when i run... | You can reduce your foot print if you don't include stdlib and make sure not to link in an libraries you don't use. All linked dlls get there own private data segment and I believe that is included in your private set.
After removing all STD libs using Yes (/NODEFAULTLIB) setting my optimizations to O1 and setting m... |
6,246,819 | 6,246,827 | How can I implement AND and OR operations in C++ | I have an assignment that I'm supposed to implement the MIPS processor in C++ and one of the MIPS instructions is "AND" and "OR" the MIPS instruction is represented as and $s1,$s2,$s3 which means that $s1=$s2(and)$s3 the $s2 and $s3 registers are represented into bits ,,, how can I perform the "AND" and "OR" operations... | There are both binary and logical and and or operators in C++.
int a, b = 1;
int x = a | b; // binary OR
int x = a & b; // binary AND
bool x = a || b; // boolean OR
bool x = a && b; // boolean AND
|
6,246,825 | 6,251,268 | Convert a prefix expression tree vector to a ORF/Karva notation expression tree vector | Ok, this is a bit of a tricky one.
I have a bunch of code that takes expression trees such that:
((a + b)/(c + d) + sqrt(e))
is stored in a vector (I'm using C++ but I just need the algorithm) in the prefix form:
+(/(+(a,b),+(c,d)),sqrt(e)) //Brackets are just to help you read it. Each operator and terminal is an eleme... | Just build a tree T. Each node is a tuple (terminal,) or (unary_operator, operand) or (binary_operator, first_operand, second_operand). The operands themselves indexes of nodes in the tree.
For instance, the expression a + (b / c), would have the tree T[0] = (+, 1, 2), T[1] = (a,), T[2] = (/, 3, 4), T[3] = (b,), T[4] =... |
6,246,877 | 6,246,916 | Unspecified template argument | I'm trying to use templates with multiple to pass data onto a function, but using only the first template argument as a filter. Something like this:
template <typename A, typename B>
class Component {
};
template <typename A>
class Context {
public:
void add(Component<A, void *> comp) {
}
}
typed... | I think what you probably need to do is change the signature of the 'add' method:
template <typename A>
class Context
{
public:
template<class B>
void add(Component<A, B> comp)
{
}
};
However, I don't know the details of your problem so this is a mere guess.
|
6,247,017 | 6,247,048 | Unexplained C++ default int values | I've been refactoring some code and I noticed some wonky behavior involving an uninitialized int array:
int arr[ARRAY_SIZE];
I set a break-point and it seems all values default to -858993460. Is there something special with this value? Any ideas why they don't default to 0?
| -858993460 is, in hex, CCCCCCCC, which Visual Studio puts as default in DEBUG MODE. This is to make it easier for you to notice that you forgot to initialize the variable. In release mode it could be anything.
I’m actually unsure why mouseBufferX isn’t an element of 10 items (if this does compile and that isn’t 10 elem... |
6,247,070 | 6,247,242 | Error implementing "AND" and "OR" in c++ | With reference to my previous question, How can i implement AND and OR operations in c++
My next question is, Sometimes it outputs some weird numbers for example 110010 & 010101 = 110591. Why does that happen?
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
long int s;
long int l;
... | For the question -- how to input binary numbers instead of decimal.
You can read them as strings, and then convert them assuming that they are base 2.
So, code like this (not tested!):
std::string s_str;
cin >> s_str;
...
// now convert as if it's a binary string, thats what the last arg following does
s = strtol(s_st... |
6,247,136 | 6,485,926 | Is event recording on time-sensitive possible? | Basic Question
Is there any way to event recording an playback within a time-sensitive (framerate independent) system?
Any help - including a simple "No sorry it is impossible" - would be greatly appreciated. I have spent almost 20 hours working on this over the past few weekends and am driving myself crazy.
Full Detai... | Answering my own question for anyone else who stumbles upon this.
Basically if you want deterministic recording and playback you need to lock the frame-rate. If the system cannot handle the frame-rate you must introduce slowdown or risk dsyncronization.
After two weeks of additional research I've decided it is just not... |
6,247,153 | 6,247,163 | Angle from 2D unit vector? | Given unit vector (0.5, 0.5) how could I find the angle (its direction)?
Is it cos(x) + sin(y)?
| Given y and x, the angle with the x axis is given by:
atan2(y, x) // note that Y is first
With (0.5, 0.5) the angle is:
radians:
In [2]: math.atan2(0.5, 0.5)
Out[2]: 0.7853981633974483
degrees:
In [3]: math.atan2(0.5, 0.5)*180/math.pi
Out[3]: 45.0
|
6,247,180 | 6,247,285 | How to have the 'string line' in the same scope as the 'getline(in,line)' in a 'while(getline(...))' loop? | Example:
std::ifstream in("some_file.txt");
std::string line; // must be outside ?
while(getline(in,line)){
// how to make 'line' only available inside of 'while' ?
}
Do-while loops won't work for the first iteration:
std::ifstream in("some_fule.txt");
do{
std::string line;
// line will be empty on first iterat... | A for loop will work, I do this all the time:
for (std::string line;
getline(in,line); )
{
}
|
6,247,321 | 6,247,328 | how can i count how many consonants are in a string so far i have this | int countConsonant(string str, int consonant)
{
int length = str.length();
consonant = 0;
for (int i = 0; i < length; i++)
{
if(str[i] == 'b'&& str[i] == 'c' && str[i] == 'd'&& str[i] == 'f'
&& str[i] == 'g'&& str[i] == 'h'&& str[i] == 'j' && str[i] == 'k'&& str[i] ... | You were close, but should check with logical-or ||, not logical-and && (str[i] simply can't be equal to two different things).
The C++03 Standard allows you to use the keywords and and or - and not, xor etc - instead of these cryptic (for new programmers) symbols, but this hasn't caught on widely - perhaps because Mic... |
6,247,396 | 6,247,439 | string::find is not finding match | Im trying to use the string::find method to determine if the string " hello " (with space before and after) exists in a line of a .txt file. if it does, its supposed to print out the line number(position isnt important). the problem is, its not finding the string. please help.
int main() {
string key (" hello ");
... | What it seems to be doing as you have it is just counting the number of lines that have that string in them. You should increment the line number var in every iteration of the loop, not just when the string is found.
int main() {
std::string key (" hello ");
ifstream myReadFile;
myReadFile.open("test.txt")... |
6,247,464 | 6,247,528 | std::transform and move semantics | I'm using Boost.Filesystem to create a listing of files in a directory. I use boost::filesystem::recursive_directory_iterator and std::copy to put each path into a std::vector as a boost::filesystem::directory_entry object. I wish to output to the file as std::strings though, so I did the following (\n to avoid the use... | This looks like a job for make_move_iterator:
std::transform(make_move_iterator(buffer.begin()),
make_move_iterator(buffer.end()), buffer_native.begin(),
[](boost::filesystem::directory_entry&& de) -> std::string
{
// still makes copy :/ perhaps native() would work better, I don't kn... |
6,247,529 | 6,247,554 | Simple SFML/C++ question, confused about literal strings and static members | I'm a bit confused by the code at http://www.sfml-dev.org/tutorials/1.6/graphics-sprite.php
Namely the code at the bottom detailing the class "Missile":
class Missile
{
public :
static bool Init(const std::string& ImageFile)
{
return Image.LoadFromFile(ImageFile);
}
Missile()
{
Sprite.SetImage(Image); // ever... | From the term, long verbose error, I am just guessing that you might have got confused with linker error. That's because, you might have either forgot to define,
static sf::Image Image;
in a .cpp file or forgot to link that .cpp file with your compilation where it's included.
Define your static member in appropriate .... |
6,247,595 | 6,247,634 | Order of calling base class constructor from derived class initialization list | struct B {
int b1, b2;
B(int, int);
};
struct D : B {
int d1, d2;
// which is technically better ?
D (int i, int j, int k, int l) : B(i,j), d1(k), d2(l) {} // 1st Base
// or
D (int i, int j, int k, int l) : d1(k), d2(l), B(i,j) {} // last Base
};
Above is just a pseudo code. In actual, I wanted to know t... | The order you refer in your question is not the "order of calling base constructor". In fact, you can't call a constructor. Constructors are not callable by the user. Only compiler can call constructors.
What you can do is to specify initializers. In this case (constructor initializer list) you are specifying initializ... |
6,247,904 | 6,247,922 | C++: Comparing two strings |
Possible Duplicate:
comparing two strings with comma seperated values
I am working in C++, where I have two strings:
string str1 = "1,4,8,",
str2 = "4,1,8,";
Both strings contains comma separated values. Now I just want to check whether all the elements in str1 also exist in str2, regardless of their positio... | As far as C++ is concerned, those strings are just sequences of characters. If you apply meaning to those characters (such as "comma separated values"), then you'll have to write some code to extract the data and deal with it.
I would do something like:
split the string on ','
convert each sequence of digits into an i... |
6,247,986 | 6,248,007 | C++: storing CSV in contianer | I have a std::string that contains comma separated values, i need to store those values in some suitable container e.g. array, vector or some other container. Is there any built in function through which i could do this? Or i need to write custom code for this?
| If you're willing and able to use the Boost libraries, Boost Tokenizer would work really well for this task.
That would look like:
std::string str = "some,comma,separated,words";
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(",");
tokenizer tokens(str, sep);
std::vect... |
6,247,996 | 6,500,629 | can HOG feature detection be used to keypoint matching? | I see HOG is often used with SVM for target detection, can it be used in matching keypoints in two images?
and btw, where could I find OpenCV sample of using HOGDescriptor?
| HOG can be used without SVM for feature matching.
just choose some points ( edge, for example ) and calculate the feature of HOG inside ROI with those points centered.
HOGDescriptor seems only for GPU programming.
I created Descriptor for HOG as a Mat in openCV and it also works for OpenCV matching functions.
|
6,248,044 | 6,248,053 | How to compare two vectors for equality element by element in C++? | Is there any way to compare two vectors?
if (vector1 == vector2)
DoSomething();
Note: Currently, these vectors are not sorted and contain integer values.
| Check std::mismatch method of C++.
comparing vectors has been discussed on DaniWeb forum and also answered.
C++: Comparing two vectors
Check the below SO post. will helpful for you. they have achieved the same with different-2 method.
Compare two vectors C++
|
6,248,282 | 6,248,945 | Creating and Exporting C++ Singleton Class from DLL | I have a small query, How to create and export Singleton class from DLL? that could be share across multiple modules of same application. My intention is to create a centralized custom logging system that would log in same file.
Any example or link will be appreciated.
| The link ajitomatix posted is for a templated singleton, a non-template solution could look like this:
class LOGGING_API RtvcLogger
{
public:
/// Use this method to retrieve the logging singleton
static RtvcLogger& getInstance()
{
static RtvcLogger instance;
return instance;
}
/// Destructor
~RtvcL... |
6,248,291 | 6,248,507 | Ignore case using boost::regex_search | How do you use boost::regex_search with the ignore case flags or constants in C++?
Please post an easy example.
Thanks!
| You need something like this
boost::regex regex("your expression here", boost::regex::icase);
boost::smatch what;
string mystring;
bool search_result = boost::regex_search(mystring.begin(),mystring.end(), what, regex);
|
6,248,304 | 6,248,325 | std:numeric_limits<double>::epsilon definition | numeric_limits::espilon returns the difference between 1 and the next double. So, should I understand that the distance between two adjacent doubles is not always the same, for instance between 2 and the next double?
And if yes could I have a piece of explanation ?
| The "density" of floating-point numbers decreases a lot as you get farther away from zero.
This is because IEEE floating-point is stored essentially as scientific notation, so range is favored over uniform precision. (If it was uniform precision, it would be fixed-point, not floating-point.)
In other words, numbers are... |
6,248,404 | 6,248,453 | C++ Exceptions - Is throwing c-string as an exception bad? | I am working on a small c++ program and learning exceptions. Is the following code "bad", and if so, what can I do to improve it?
try {
// code
if (some error) {
throw "Description of error.";
}
}
catch (char* errorMessage) {
cerr << errorMessage << endl << "Fatal error";
}
Is there anything wr... | It is much better to throw a standard exception object. In general, the best practice is to throw something derived from std::exception so that if in some situation it does cause your program to terminate, the implementation has a better chance of printing a useful diagnostic.
Because it isn't hard to do this, I would ... |
6,248,617 | 6,254,091 | send varint without deleting CodedOutputStream, ZeroCopyOutputStream | My application sends varints many times. Every time I have to allocate memory for 2 objetcs: CodedOutputStream and FileOutputStream and later relese it. IMO it is unnecessary time loss. How can I send the varint without all this process? (I don't want to do it manually but with protobuf)
I have found it:
delete coded_... | You don't have to allocate the CodedOutputStream on the heap, you can just declare it as a local variable (or class member) where you need it. It doesn't look like the constructor is particularly expensive.
Are you always writing to the same file? If so you can just use a single CodedOuputStream and FileOutputStream fo... |
6,248,631 | 6,248,643 | Can NULL pointer after "dynamic_cast" actually be dereferenced? | The following code compiles correctly and get the mysterious output:
special Investment function
00000000
(Environment: C++ VS2010)
#include <iostream>
#include <vector>
using namespace std;
class Security {
public:
virtual ~Security() {}
};
class Stock : public Security {};
class Investment : public Security... | Dereferencing a null pointer is undefined behavior - you can get unexpected results. See this very similar question.
In this case Investment::special() is called in a non-virtual way, so you can think the compiler just creates a global function
Investment_special_impl( Investment* this )
and calls it passing a null th... |
6,248,700 | 6,248,740 | Templates for code which is similar but not identical? | I have a bunch of functions which read completely identical except for one line of code, which is different depending on the type of input parameter.
Example:
void Func(std::vector<int> input)
{
DoSomethingGeneral1();
...
DoSomethingSpecialWithStdVector(input);
...
DoSomethingGeneral2();
}
void Func(int... | here you go..
changed the parameters to references to avoid copies + assure you can use the changed values again in Func()
void DoSomethingSpecial( std::vector<int>& input ){}
void DoSomethingSpecial( int& input ){}
void DoSomethingSpecial( std::string& input ){}
template< typename T >
void Func( T input )
{
DoSom... |
6,249,468 | 6,251,263 | representation of double and radix point | According to what I know on double (IEEE standard) there is one bit for signus, 54 bits for mantissa, a base and some bits for exponent
the formula to get the double is : (−1)^s × c × b^q
Maybe I made some mistake but the idea is here.
I'm just wondering how we can know where to put the radix point with this formula.
I... | 32 = 1 * 2^5, so mantissa=1, exponent=5, sign=0. We need to add 1023 to exponent when coding the exponent, so below we have 1023+5=1028. Also we need to remove digit 1 when coding mantissa, so that 1.(whatever) becomes (whatever)
Hexadecimal representation of 32 as 64-bit double is 4040000000000000, or binary:
0100 000... |
6,249,522 | 6,250,342 | Loading meshes from .obj (or any other) File into DirectX9/C++ project | Currently I have a 3D Cube that I drew by writing coordinates, that can rotate and move on a black screen.
Now I have a Model that I created in "3Ds Max"(It's a little backyard with high stonewalls, so I'm trying to use it as my world object.) and I want to load this model into my DirectX9/C++ project.
As far as I see ... | AFAIK, DirectX does not support wavefront object files out of the box. You will need an external mesh loader for that purpose.
I can remember, that in the DX 10 SDK is a sample of how to load an .obj file, I think the sample is called MeshFromOBJ10. I don't know if it is of any use in DirectX 9.
As far as I know, the s... |
6,249,533 | 6,249,555 | What is the complexity of the below program? | What is the complexity of the below program? I think it must be O(n), since there is a for loop that runs for n times.
It is a program to reverse the bits in a given integer.
unsigned int reverseBits(unsigned int num)
{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0;
int i;
for ... | If n is the input number, then NO_OF_BITS is O(log n) (think about it: to represent a binary number n, you need about log2(n) bits).
EDIT: Let me clarify, in the light of other responses and comments.
First, let n be the input number (num). It's important to clarify this because if we consider n to be NO_OF_BITS instea... |
6,249,829 | 6,258,149 | How do I set up an XUL document to be the front end of a application using Gecko? | How do I set up an XUL document to be the front end of a application using Gecko or XUL Runner?? Or is there no way to do it? Could someone provide an brief example if it is possible? Or link to a website?
From what I've read, it can't be a standalone application, and it involves using XPCOM.
| Creating XPCOM Components from the Mozilla developers' network seems to be quite a good guide. It walks you through creating a XPCOM component with every step. That guide might be a bit hard to understand though, and Creating a C++ XPCOM Component from iosart.com might be easier
Firefox addons developer guide / Using X... |
6,249,979 | 7,950,176 | HTTP Streaming: what realizations of Push Technology are available? | I'm currently in search of an usable realizations of http Push Technology. At least it must support channel subscription and channel publication.
What convenient implementations in C++ (or C) are available?
| Only thing that comes to mind (in C++) that supports server push and self contains a httpd is Wt. It's actually remarkably easy to get installed, compile a program, and get running. I didn't have any Qt background. If you do that will make it even easier for you.
|
6,250,304 | 6,250,396 | return a scope in C++ | I encountered the following code in a file (looks like header file) iomanip of gcc 4.5.1:
inline _Setbase
setbase(int __base)
{ return { __base }; }
what is the language definition of returning a scope (block)?
| Looks like the new syntax for Uniform initialization in C++0x to me.
|
6,250,411 | 6,251,366 | dot product of complex vectors with openMP | I'm using a version of openMP which does not support reduce() for complex argument. I need a fast dot-product function like
std::complex< double > dot_prod( std::complex< double > *v1,std::complex< double > *v2,int dim )
{
std::complex< double > sum=0.;
int i;
# pragma omp parallel shared(sum)
# pragma omp for... | Each thread can calculate the private sum as the first step and as the second step it can be composed to the final sum. In that case the critical section is only needed in the final step.
std::complex< double > dot_prod( std::complex< double > *v1,std::complex< double > *v2,int dim )
{
std::complex< double > sum=0.;
... |
6,250,682 | 6,251,767 | Cannot Call .Net Service From C++ | I have written a .NET Windows service which has a WCF service built into it. I can call this from a C# client written in Visual Studio 2010. However, I also need to call it from a MFC app written in Visual Studio 6. I have added COM Interop code to try and achieve this, created a snk file, used regasm to register it an... | Perhaps this will help. Looks way more complicated than i would have guessed :)
Create WCF service for unmanaged C++ clients
good luck
|
6,251,160 | 6,251,190 | What is the meaning of double curly braces initializing a C-struct? | I'm currently working with legacy C++ code, successfully compiled with gcc 2.9.X.
I've been asked to port this legacy code to gcc 3.4.X. Most of the errors were easily corrected, but this particular one puzzles me.
The context :
struct TMessage
{
THeader header;
TData data;
};
struct THeader
{
... | It initialises all fields of the POD structure to 0.
Rationale:
const SomeStruct init = {Value};
Initialises the first field of SomeStruct to Value, the rest of the structure to zero (I forget the section in the standard, but it's there somewhere)
Thus:
const SomeOtherStruct init = {{Value}};
Initialises the first fi... |
6,251,237 | 6,251,673 | Are methods in the pimpl inlined? | Considering next simple example:
The header:
// a.hpp
#ifndef A_HPP
#define A_HPP
#include <memory>
class A
{
public:
A();
int foo();
private:
struct Imp;
std::auto_ptr< Imp > pimpl;
};
#endif // A_HPP
The implementation :
// a.cpp
#include "a.hpp"
struct A::Imp
{
int foo()
{
// do something and... | Herb Sutter once made a great article about inlining.
The first question to ask is: when can inlining happen ?
In C++:
it may happen at the compilation stage
it may happen at the link stage (LTO: Link Time Optimization)
Both times, the mechanism is similar: if the compiler/linker knows about the implementation of the... |
6,251,373 | 6,251,395 | hash_map value deletion | My question concern memory management.
I got this container :
typedef hash_map<const string, Powerdomain*, strptrhash, strptrequal> PowerdomainHashMap;
now I add one element in it
PowerdomainHashMap powerdomainMap;
Powerdomain* pd1=new Powerdomain("Powerdomain1");
powerdomainMap.insert(Powerdomain_pair(pd1->getN... |
Is a powerdomainMap.clear() sufficient ?
No. You have manually acquired memory (using new), you need to manually release it (using delete). Better to use smart pointers instead of raw pointers though (preferably std::shared_ptr).
|
6,251,536 | 6,251,557 | Const procedure in C++, weird error in Visual Studio C++ 2010? | class a{
public:
int b;
static int c;
virtual void mod() const
{
c=4;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
a bi;
return 0;
}
Look at this ... After compiling it using Visual Studio C++ 2010 compiler, I get...
cpplearningconsole.obj : error
LNK2001: unresolved external sym... | You have just declared the static variable in the class definition, you need to define it in the by doing int a::c = 0;.
|
6,251,707 | 6,251,839 | Default initialization in C++ | I was asking myself something this morning, and I can't find the words to properly "google" for it:
Lets say I have:
struct Foo
{
int bar;
};
struct Foo2
{
int bar;
Foo2() {}
};
struct Foo3
{
int bar;
Foo3() : bar(0) {}
};
Now if I default instantiate Foo, Foo2 and Foo3:
Foo foo;
Foo2 foo2;
Foo3 foo3;
... | Only foo3 will be in all contexts. foo2 and foo will be if they are of static duration. Note that objects of type Foo may be zero initialized in other contexts:
Foo* foo = new Foo(); // will initialize bar to 0
Foo* foox = new Foo; // will not initialize bar to 0
while Foo2 will not:
Foo2* foo = new Foo2(); // will ... |
6,251,889 | 48,068,809 | Type condition in template | Is it possible to build only some part of the code given the type of the template in C++ ?
It would be something lake that :
#include <iostream>
using namespace std;
template<typename T>
void printType(T param)
{
#if T == char*
cout << "char*" << endl;
#elif T == int
cout << "int" << endl;
... | Since C++17 there is a way to do exactly this with if-constexpr. The following compiles since clang-3.9.1, gcc-7.1.0, and recent MSVC compiler 19.11.25506 handles well too with an option /std:c++17.
#include <iostream>
#include <type_traits>
template<typename T>
void printType(T)
{
if constexpr (std::is_same_v<T, ... |
6,252,146 | 6,253,705 | QT threads :Getting QObject::startTimer: timers cannot be started from another thread warning | I follow the examples from the Qt SDK, starting timer in the QThread Subclass
but I keep getting the warning and the thread never starts the timer.
Here is the code:
NotificationThread::NotificationThread(QObject *parent)
:QThread(parent),
m_timerInterval(0)
{
moveToThread(this);
}
Notificati... | If you add the line
m_NotificationTimer.moveToThread(this);
to beginning of run() method of your thread from that point on your timer object will invoke the connected slot within the your thread.
When you first create the timer it will run within your main thread. By moving it to your own thread as above the moveToTh... |
6,252,191 | 6,290,898 | Wordcount C++ Hadoop pipes does not work | I am trying to run the example of wordcount in C++ like this link describes the way to do :
Running the WordCount program in C++. The compilation works fine, but when I tried to run my program, an error appeared :
bin/hadoop pipes -conf ../dev/word.xml -input testtile.txt -output wordcount-out
11/06/06 14:23:40 WAR... | I do not know if I have to answer to my question in this way, or edit my question. Anyway I find the solution and I just want to tell it for everyone who will get the same error.
After few days of research and try, I understand that Fedora and C++ on 64bits for Hadoop is not a good match. I tried to compile the Hadoop ... |
6,252,300 | 6,252,390 | declaring a class member function as friend of a template class | #include< iostream>
using namespace std;
template< class t>
class X
{
private:
t x;
public:
template< class u>
friend u y::getx(X< u> );
void setx(t s)
{x=s;}
};
class y
{
public:
template< class t>
t getx(X< t> d) ... | You should "forward declare" class y before template class X. I.e., just put:
class y; // forward declaration
template
class X...
|
6,252,356 | 6,256,105 | Browser Helper Object cannot load module? | I am creating a Browser Helper Object in C++, and previous tests were successful on multiple machines. However, the final product only works on the computer that it was developed on. The .dll file was tested on computers with similar settings, such as the same Operating System, and the only thing that had changed to ma... | I bet this one is causing the problem: MSVCR100D.dll. That is a debug version of the C runtime. What you want to do is statically link CRT by using the /MT option. More details here: http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
|
6,252,468 | 6,253,913 | Instantiating a Qt File-Based Logger for Debugging in a C++ Library | The following page provides a nice simple solution for file based logging in Qt for debugging without using a larger logging framework like the many that are suggested in other SO questions.
I'm writing a library and would like to instantiate a logger that the classes in the library can use (mostly for debugging purpos... | I pretty much agree with OrcunC but I'd recommend making that ofstream a little more accessible and capable of handling the Qt value types.
Here's my recommended process:
Create a global QIODevice that to which everything will be written. This will probably be a QFile.
Create a QTextStream wrapper around that QIODevic... |
6,252,558 | 6,252,861 | Remove specific items from a listbox in MFC | CString dance[] = {L"Atb", L"Tiesto", L"Madonna", L"Paul van Dyk", L"Armin van Burren", L"Jennifer Lopez"};
for(int i = 0; i < m_ItemsListBox.GetCount(); ++i)
{
CString item;
int length = m_ItemsListBox.GetTextLen(i);
m_ItemsListBox.GetText(i, item.GetBuffer(length));
for(int j = 0; j < sizeof(dance)/s... | Hmmm I wouldn't be comfortable deleting things from the list box while iterating through the items in the listbox seems to be asking for problems down the line.
Honestly you could do something like this, I've just whipped together - construct a list of all the item indexes you want to remove and remove them at the end.... |
6,252,864 | 6,252,948 | Are uninitialized pointers in objects with static storage duration initialized to NULL, or to all-zeros? | out of curiousity and because I don't have my copy of the standard at hand right now:
Given an implementation where null pointers are not represented by an all-zeros pattern, will uninitialized pointer members of objects with static storage duration be initialized to the proper null pointer value, or to an all-zeros va... | The standard says (8.5/4):
To zero-initialize an object of type T
means:
— if T is a scalar type, the object is set to the value 0
(zero), taken as an integral constant
expession, converted to T
— if T is a non-union class type, each non-static data member and each
base-class subobject is zero-initialized;
So... |
6,252,909 | 6,253,331 | array as rvalue on single line which works with C++2003? | I am parsing some text and it would make my life easier if i can use arrays are rvalues rather then defining it on their own line. I have done this
int a[]={1,2,3}; //its own line. Do not want
and
func([]()->int*{static int a[]={1,2,3}; return a; }()); //It compiles but untested. It doesn't compile with 2003
i trie... | func([]()->int*{int a[]={1,2,3}; return a; }()); //works well on C++0x.
I find interesting the comment works well. I am not a lambda lawyer, but I believe that the code above is returning a pointer into a local variable, and that is undefined behavior, so even if that compiles that does not mean that it is correct.
As... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.