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 |
|---|---|---|---|---|
2,859,801 | 2,859,894 | How do I connect two apps | I am considering building an app in C++ that will be parsing text from the web and create some statistical results. These results I want to be fed in an external app in real time. The external app (to whose code I have no access, but can ask for a - paid - custom made addition) will then need some code to read and use these results.
I am wondering what would be the best way to interconnect the two apps, in terms of speed and ease of implementation. I am considering :
disk I/O (slow)
a Windows service
a DLL
a web service
a web page
Perhaps I am missing a better solution ? Thank you.
Update : there is an additional need to know how long a data request may take at worst.
| There are a number of IPC mechanisms to choose from from (sockets, shared memory, pipes, ...). I guess the "best choice" will depend to a large extend on how the other application is structured aka. how much your custom extension will cost you.
I don't know much of your environment but it might be worthwhile to have a look at boost.interprocess:
http://www.boost.org/doc/libs/1_43_0/doc/html/interprocess.html
|
2,859,950 | 2,859,995 | Register management tips | Implementing a custom VM and I've come to use registers (these will store pointers and will be NULL when empty). But, I've come to realize that I actually have no idea how to manage register-based memory. Like, what do I do if all my registers are used up and some code wants another? Preferably, without just creating a new one.
This is in C++.
| I don't think this is a problem of the machine, instead it is a problem of the programmer of the machine. What you can do(IMO) is just to provide the means to move the values of the registers into memory back and forth. Problem solved :)
|
2,859,980 | 2,859,997 | Conversion between classes | Let's say we have a class called A and another one called B.
and we want to have a conversion method that converts A to B.
In the software architecture point of view, which one is preferred?
write A.export()
write B.import()
write a converter class, i.e. convert(A, B) or Convert(A) or ...
if the language matters, I'm using C++
| It entirely depends on how you intend to use it, but in many cases, the cleanest way to do this is to implement a converting constructor:
class B { };
class A
{
A(const B& b) { }
};
B b;
A a = b; //< calls converting constructor
(of course, you could implement a converting constructor for converting from A to B, as well)
|
2,860,006 | 2,879,303 | Good code visualization / refactoring tools for C++? | I've found myself coming across a lot of reasonably large, complicated codebases at work recently which I've been asked to either review or refactor or both. This can be extremely time consuming when the code is highly concurrent, makes heavy use of templates (particularly static polymorphism) and has logic that depends on callbacks/signals/condition variables/etc.
Are there any good visualization tools for C++ period, and of those are there any that actually play well with "advanced" C++ features? Anything would probably be better than my approach now, which is basically pen+paper or stepping through the debugger. The debugger method can be good for following a particular code path, but isn't great for seeing the big picture you really need when doing serious refactoring.
EDIT: I should mention that Visual Studio plugins aren't going to be a lot of help to me, since our stuff is mostly Linux-only.
| There is a KDevelop plugin for code visualization:
http://liveblue.wordpress.com/2009/08/21/gsoc-wrap-up-static-code-visualization-in-kdevelop/
|
2,860,068 | 2,860,086 | Linkage of namespace functions | I have a couple of methods declared at the namespace level within a header for a class:
// MyClass.h
namespace network {
int Method1(double d);
int Method2(double d);
class MyClass
{
//...
}
}
then defined in
//MyClass.cpp
int
Method1(double d)
{ ... }
int
Method2(double d)
{ ... }
This project compiles cleanly and is a dependency for a ui project which uses MyClass. The functions were previously member functions of MyClass, but were moved to namespace since it was more appropriate.
My problem is the ui project complains when it gets to the linker:
1>network.lib(MyClass.obj) : error LNK2001: unresolved external symbol "int __cdecl network::Method1(double)" (?INT@ds@sim@@YAHN@Z)
1>network.lib(MyClass.obj) : error LNK2001: unresolved external symbol "int __cdecl network::Method2(double)" (?CINT@ds@sim@@YAHN@Z)
What am I doing wrong?
| It looks like you've put the function declarations inside a namespace block, but forgotten to put the function implementations inside a namespace block as well. Try:
namespace network {
int
Method1(double d)
{ ... }
int
Method2(double d)
{ ... }
}
|
2,860,252 | 2,860,273 | g++ doesn't think I'm passing a reference | When I call a method that takes a reference, g++ complains that I'm not passing a reference. I thought that the caller didn't have to do anything different for PBR. Here's the offending code:
//method definition
void addVertexInfo(VertexInfo &vi){vertexInstances.push_back(vi);}
//method call:
sharedVertices[index]->addVertexInfo(VertexInfo(n1index, n2index));
And here's the error:
GLUtils/GLMesh.cpp: In member function 'void GLMesh::addPoly(GLIndexedPoly&)':
GLUtils/GLMesh.cpp:110: error: no matching function for call to 'SharedVertexInfo::addVertexInfo(VertexInfo)'
GLUtils/GLMesh.h:93: note: candidates are: void SharedVertexInfo::addVertexInfo(VertexInfo&)
| VertexInfo(n1index, n2index) creates a temporary VertexInfo object. A temporary cannot be bound to a non-const reference.
Modifying your addVertexInfo() function to take a const reference would fix this problem:
void addVertexInfo(const VertexInfo& vi) { /* ... */ }
In general, if a function does not modify an argument that it takes by reference, it should take a const reference.
|
2,860,390 | 2,860,421 | Cannot refer to a template name nested in a template parameter | I have the following code:
template <typename Provider>
inline void use()
{
typedef Provider::Data<int> D;
}
Where I'm basically trying to use a template class member 'Data' of some 'Provider' class, applied to 'int', but I get the following errors:
util.cpp:5: error: expected init-declarator before '<' token
util.cpp:5: error: expected `,' or `;' before '<' token
I'm using GCC 4.3.3 on a Solaris System.
| typedef typename Provider::template Data<int> D;
The problem is that, when the compilers parses use() for the first time, it doesn't know Provider, so it doesn't know what Provider::Data refers to. It could be a static data member, the name of a member function or something else. That's why you have to put the typename in.
The additional template is necessary whenever the nested name is the name of a template. If it was something else, then Data < ... could be a comparison.
|
2,860,475 | 2,860,672 | How to access CWebBrowser class instance (defined in a protected class) in a different class? C++ | I have been playing with this webbrowser control example
I got it working and added some timers using ON_WM_TIMER.
Now I would like to access the m_Browser (CWebBrowser class instance) defined inside the protected CMyBrowserView class into a different class. (for example CMyBrowserApp in the code sample) and use .Navigate and other functions.
How can I do this?
(im using visual studio 6 c++)
| Create a subclass of CMyBrowserView and add a method for each of the things you want the
browser to do. The method should call the appropriate method on m_Browser.
E.g.
class CBrowserViewEx : public CMyBrowserView
{
...
void Navigate(LPCTSTR URL, VARIANT* Flags,
VARIANT* TargetFrameName, VARIANT* PostData,
VARIANT* Headers)
{
m_Browser.Navigate(URL, Flags, TargetFrameName, PostData, Headers);
}
...
}
That way you can access the functionality from outside, but still limit who can do what with the browser control and you can add extra wrapper code (such as parameter checking) if you need to.
(Edit) Also note you'll need to change the code in MyBrowser.cpp to pass the new view name into the new CSingleDocTemplate, so MFC automatically creates your new view for you.
|
2,860,524 | 2,860,611 | qapps runs well but breakpoint sometimes generates segmentation fault | I have a qApp that generates a segmentation fault only when a breakpoint is inserted in the code (I can put it at different places) and only after 4-5 breakpoint stops. Do I have a problem with my code or is this a DBG bug. the method is part of a QThread Class.
Basically what I did is i took the mandlebrot example, and have 3 instances of it in my program. So the program would look like a mainwindow that has 3 mandlebrot widgets in it, one besides the other. Is it possible that GDB doesnt support debugging qthread subclasses that are instantiated multiple times or is it thread-unsafe to do so. I dont have any problems at run-time.
| It looks like the problem is that you have unsynchronized access to some object in your code and breakpoints are happily allows you to see the problem.
|
2,860,593 | 2,860,632 | What is the difference between Visual C++ and C++? | Well here's a rather stupid question. Is Visual C++ JUST an IDE?? Or is it a language on its own for win32? What exactly would be the difference between the two? This I ask because I was trying out some of my old C++ code on VC++ 2008 and it wouldn't compile.
| Visual C++ can be many things, including:
Microsoft's C++ compiler (cl.exe, link.exe etc)
The IDE (Visual Studio in C++ mode)
The C runtime (MSVCRT)
Other libraries (less so): MFC, ATL
As for compiling old C++ code: Visual Studio is now a fairly compliant C++ compiler. This was not always the case, such as with Visual C++ 6 or earlier. It is likely your code is not standards compliant or uses deprecated behavior, which simply doesn't work on newer compilers.
Note: this paragraph is outdated: Visual C++ is unfortunately a poor C compiler, as it does not support C99 (and never will), unless features overlap between C++ and C99. The most notable issue for many people is the lack of stdint.h.
Visual C++ supports C11 and C17 starting with Visual Studio 2019 version 16.8 Preview 3
For many years Visual Studio has only supported C to the extent of it
being required for C++. Things are about to change now that a
conformant token-based preprocessor has been added to the compiler.
With the advent of two new compiler switches, /std:c11 and /std:c17,
we are officially supporting the latest ISO C language standards.
|
2,860,634 | 2,860,690 | Checking for duplicates in a vector |
Possible Duplicate:
Determining if an unordered vector<T> has all unique elements
I have to check a vector for duplicates. What is the best way to approach this:
I take the first element, compare it against all other elements in the vector. Then take the next element and do the same and so on.
Is this the best way to do it, or is there a more efficient way to check for dups?
| Use a hash table in which you insert each element. Before you insert an element, check if it's already there. If it is, you have yourself a duplicate. This is O(n) on average, but the worst case is just as bad as your current method.
Alternatively, you can use a set to do the same thing in O(n log n) worst case. This is as good as the sorting solution, except it doesn't change the order of the elements (uses more memory though since you create a set).
Another way is to copy your vector to another vector, sort that and check the adjacent elements there. I'm not sure if this is faster than the set solution, but I think sorting adds less overhead than the balanced search trees a set uses so it should be faster in practice.
Of course, if you don't care about keeping the original order of the elements, just sort the initial vector.
|
2,860,673 | 2,860,739 | Initializing a C++ vector to random values... fast | Hey, id like to make this as fast as possible because it gets called A LOT in a program i'm writing, so is there any faster way to initialize a C++ vector to random values than:
double range;//set to the range of a particular function i want to evaluate.
std::vector<double> x(30, 0.0);
for (int i=0;i<x.size();i++) {
x.at(i) = (rand()/(double)RAND_MAX)*range;
}
EDIT:Fixed x's initializer.
| Right now, this should be really fast since the loop won't execute.
Personally, I'd probably use something like this:
struct gen_rand {
double range;
public:
gen_rand(double r=1.0) : range(r) {}
double operator()() {
return (rand()/(double)RAND_MAX) * range;
}
};
std::vector<double> x(num_items);
std::generate_n(x.begin(), num_items, gen_rand());
Edit: It's purely a micro-optimization that might make no difference at all, but you might consider rearranging the computation to get something like:
struct gen_rand {
double factor;
public:
gen_rand(double r=1.0) : factor(range/RAND_MAX) {}
double operator()() {
return rand() * factor;
}
};
Of course, there's a really good chance the compiler will already do this (or something equivalent) but it won't hurt to try it anyway (though it's really only likely to help with optimization turned off).
Edit2: "sbi" (as is usually the case) is right: you might gain a bit by initially reserving space, then using an insert iterator to put the data into place:
std::vector<double> x;
x.reserve(num_items);
std::generate_n(std::back_inserter(x), num_items, gen_rand());
As before, we're into such microscopic optimization, I'm not at all sure I'd really expect to see a difference at all. In particular, since this is all done with templates, there's a pretty good chance most (if not all) the code will be generated inline. In that case, the optimizer is likely to notice that the initial data all gets overwritten, and skip initializing it.
In the end, however, nearly the only part that's really likely to make a significant difference is getting rid of the .at(i). The others might, but with optimizations turned on, I wouldn't really expect them to.
|
2,860,691 | 2,861,709 | IE Address bar search. I need to add a list of other results at the end of current result list | Currently, if you type in the address bar in IE, you see a dropdown list of url search results depending on what you type.
I'd like any hint, anything, about how to access the address bar object throught a BHO in C++, so that
i can append url results from my bho at the end the current list.
Thank you.
If anyone need precisions, please ask. I'll be checking for responses every single days.
| There is no direct way to do this. You can add your urls to History using IUrlHistoryStg, and then they will show up if they match what the user types.
|
2,860,722 | 2,860,869 | linker error when using tr1::regex | I've got a program that uses tr1::regex, and while it compiles, it gives me very verbose linker errors.
Here's my header file MapObject.hpp:
#include <iostream>
#include <string>
#include <tr1/regex>
#include "phBaseObject.hpp"
using std::string;
namespace phObject
{
class MapObject: public phBaseObject
{
private:
string color; // must be a hex string represented as "#XXXXXX"
static const std::tr1::regex colorRX; // enforces the rule above
public:
void setColor(const string&);
(...)
};
}
Here's my implementation:
#include <iostream>
#include <string>
#include <tr1/regex>
#include "MapObject.hpp"
using namespace std;
namespace phObject
{
const tr1::regex MapObject::colorRX("#[a-fA-F0-9]{6}");
void MapObject::setColor(const string& c)
{
if(tr1::regex_match(c.begin(), c.end(), colorRX))
{
color = c;
}
else cerr << "Invalid color assignment (" << c << ")" << endl;
}
(...)
}
and now for the errors:
max@max-desktop:~/Desktop/Development/CppPartyHack/PartyHack/lib$ g++ -Wall -std=c++0x MapObject.cpp
/tmp/cce5gojG.o: In function std::tr1::basic_regex<char, std::tr1::regex_traits<char> >::basic_regex(char const*, unsigned int)':
MapObject.cpp:(.text._ZNSt3tr111basic_regexIcNS_12regex_traitsIcEEEC1EPKcj[std::tr1::basic_regex<char, std::tr1::regex_traits<char> >::basic_regex(char const*, unsigned int)]+0x61): undefined reference tostd::tr1::basic_regex >::_M_compile()'
/tmp/cce5gojG.o: In function bool std::tr1::regex_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, char, std::tr1::regex_traits<char> >(__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::tr1::basic_regex<char, std::tr1::regex_traits<char> > const&, std::bitset<11u>)':
MapObject.cpp:(.text._ZNSt3tr111regex_matchIN9__gnu_cxx17__normal_iteratorIPKcSsEEcNS_12regex_traitsIcEEEEbT_S8_RKNS_11basic_regexIT0_T1_EESt6bitsetILj11EE[bool std::tr1::regex_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, char, std::tr1::regex_traits<char> >(__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::tr1::basic_regex<char, std::tr1::regex_traits<char> > const&, std::bitset<11u>)]+0x53): undefined reference tobool std::tr1::regex_match<__gnu_cxx::__normal_iterator, std::allocator > >, std::allocator, std::allocator > > > >, char, std::tr1::regex_traits >(__gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, std::tr1::match_results<__gnu_cxx::__normal_iterator, std::allocator > >, std::allocator, std::allocator > > > > >&, std::tr1::basic_regex > const&, std::bitset<11u>)'
collect2: ld returned 1 exit status
I can't really make heads or tails of this, except for the undefined reference to std::tr1::basic_regex near the beginning. Anyone know what's going on?
| Regex support for C++0x is incomplete and wasn't there for TR1, see the implementation status page for C++0x/TR1.
Boost offers an alternative TR1 implementation as well as the original library it is based on.
|
2,860,846 | 2,860,857 | IE status bar. I need to add a clickable icon to the status bar | My bho (Browser Helper Object) is a sidebar (right-sided iframe) that needs to be opened/closed by clicking the status bar icon in IE (IE8). I didn't find any informations for clickable icons. Anyone knows wich interface to use to do that. Thank you. (I'm using ATL: Active Template Library).
If anyone need precisions, please ask. I'll be checking for responses every single days.
| Modification of IE's Status Bar by add-ons is not supported and is likely to cause reliability and performance problems across IE versions. You should consider using a Menu item instead, as Menu items ARE supported extensibility points.
|
2,860,968 | 2,861,420 | Qtimer not timing out QT, C++ | I am learning C++ and using QT.
I have a small program in which I am trying to update the text of the PushButton every second. The label being current time. I have a timer that should time out every second, but seems like it never does. here's the code.
Header File
#ifndef _HELLOFORM_H
#define _HELLOFORM_H
#include "ui_HelloForm.h"
class HelloForm : public QDialog {
public:
HelloForm();
virtual ~HelloForm();
public slots:
void textChanged(const QString& text);
void updateCaption();
private:
Ui::HelloForm widget;
};
#endif /* _HELLOFORM_H */
CPP file
#include "HelloForm.h"
#include <QTimer>
#include <QtGui/QPushButton>
#include <QTime>
HelloForm::HelloForm(){
widget.setupUi(this);
widget.pushButton->setText(QTime::currentTime().toString());
widget.pushButton->setFont(QFont( "Times", 9, QFont::Bold ) );
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateCaption()));
timer->start(1000);
connect(widget.pushButton, SIGNAL(clicked()), qApp, SLOT(quit()) );
connect(widget.nameEdit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&)));
}
HelloForm::~HelloForm() {
}
void HelloForm::textChanged(const QString& text) {
if (0 < text.trimmed().length()) {
widget.helloEdit->setText("Hello " + text.trimmed() + "!");
} else {
widget.helloEdit->clear();
}
}
void HelloForm::updateCaption() {
QString myVar;
myVar = QTime::currentTime().toString();
widget.pushButton->setText(myVar);
}
Any help will be greatly appreciated... The PushButton's text never changes...
| You don't include the Q_OBJECT macro at the beginning of your class. You need it if your class declares any signals or slots (at least, if you want them to work). In fact, it's generally a good practice to include it in any class that is derived from QObject.
Modify your class declaration to look like this:
class HelloForm : public QDialog {
Q_OBJECT;
public:
// Actual code here.
};
http://doc.qt.io/qt-5/qobject.html#Q_OBJECT
|
2,860,997 | 2,861,066 | Accessing initialized variable on different class C++ | I'm having some difficulties with this problem.
The main idea is, I initialized a variable of class type B in class A, class A.h has the variable Z declared as public, like B *Z;
In class A.cpp, I initialized it as Z = new B();
Now, I want to access that variable from class C and I'm unable to do so. C.h includes A.h and B.h
Here goes a bit of code:
Car.h
#include "Model.h"
class Car {
public:
static Model *Z;
}
Car.cpp
#include "Car.h"
void Car::init() {
Z = new Model();
}
Model.h
Class Model {}
Camera.h
#include "Model.h"
#include "Car.h"
class Camera {}
Camera.cpp
Camera::init() {
Car::Z->getPos();
}
|
I initialized a variable of class type
B in class A
#pragma once
#include "B.h"
class A
{
public:
B* Z;
A()
{
Z = new B();
}
}
B.h
#pragma once
class B
{
}
C.h
#pragma once
#include "A.h"
class C
{
A a; //here you construct A
C()
{
a.Z = new B(); //you can read/write Z
}
}
This should work! Be careful to include the #pragma once or a header guard/include guard (http://en.wikipedia.org/wiki/Header_file) so the headers won't be included twice (if should have done it).
There are 3 classes, car, model and
camera. in car I declare a new model Z
and I want the camera to follow that
model so I'll have to access the model
positions in camera class
A = Car
B = Model
C = Camera
|
2,861,101 | 2,861,356 | Static initialization of a struct with class members | I have a struct that's defined with a large number of vanilla char* pointers, but also an object member. When I try to statically initialize such a struct, I get a compiler error.
typedef struct
{
const char* pszA;
// ... snip ...
const char* pszZ;
SomeObject obj;
} example_struct;
// I only want to assign the first few members, the rest should be default
example_struct ex = { "a", "b" };
SomeObject has a public default constructor with no arguments, so I didn't think this would be a problem. But when I try to compile this (using VS), I get the following error:
error C2248: 'SomeObject::SomeObject' : cannot access private member declared in class 'SomeObject'
Any idea why?
Update: Here's the definition of SomeObject
class SomeObject
{
void operator=(const SomeObject&);
SomeObject(const SomeObject&);
public:
SomeObject()
{
// etc
}
// members snipped
}
| Your initialization of ex performs copy-initialization. It takes the value on the right and uses it to initialize the variable on the left. For class-type members, the appropriate constructor is used. In your case, that means invoking the copy constructor for SomeObject, but you've made that constructor private, so the compiler is correct in telling you that SomeObject::SomeObject is a private member that can't be accessed.
Although the compiler is allowed to elide the call to the copy constructor and initialize ex.obj directly with the default constructor, that is an optional optimization; it still needs to be allowed to call the copy constructor.
You can either give example_struct a constructor of your own and use that in place of brace initialization, or you can publicize SomeObject's copy constructor.
|
2,861,216 | 2,861,698 | Browser tabs create multiple instances of my sidebar for each tab; I only want one sidebar | I have a sidebar (iframe). The problem is, if you open a second tab (in the same browser) it creates a new instance of the same sidebar. That means i have now 2 sidebars. In exemple, if i close the sidebar in the first tab, i would like to have it closed in the second tab as well.
Is it possible to have only one instance of a sidebar in a browser, so that even if i open a new tab, the sidebar is not affected. (the goal is to interact with evey pages we visit with one sidebar. If anyone needs more precise information, please ask. I'll be checking for responses every single day.
| You can't change how IE works, so if you really want to do this, you have hoops you need to jump through, or you can fake it.
You can fake it by just living with multiple instances and synchronizing their state yourself.
If you really want to have just one, you can have your sidebar be simple a host for a child window. The child window is where all your functionality lives and you just re-parent the child window as the user switches tabs. However, there are some subtle issues there since IE8 allows different tabs to be in different processes, and re-parenting windows cross process has all sorts of implications (like attaching input queues and what if the creating process terminates). I'd recommend faking it.
|
2,861,270 | 2,861,312 | returning an abstract class from a function | Is it possible to return an abstract class(class itself or a reference, doesn't matter) from a function?
| You can return an abstract class pointer - assuming B is a concrete class derived from abstract class A:
A * f() {
return new B;
}
or a reference:
A & f() {
static B b;
return b;
}
or a smart pointer:
std::unique_ptr<A> f() {
return std::make_unique<B>(...);
}
|
2,861,366 | 2,861,391 | Demystifying gcc under lpthreads | in these days i'm playing with thread library and trying to implement some functions.
One of the tutorial says that to run the program use :
gcc -lpthread -lrt -lc -lm project1.c scheduler.c -o out
first of all i need deep understanding of what is gcc doing in each line,
lpthread is used for what? what are the contributions of lrt -lc -lm ?
project1.c and scheduler.c is compiled together so what should i understand? i checked
the code and any of them not included in project1.c or scheduler.c.
as an output clearly it gives "out".
secondly the author states that to run the program you have to use
./out number filename (For example, ./out 2 sample.txt)
To make these clear as far as i understand the main function gets number and sample.txt as an input.(?)
thanks for your answers and making me clear.
| -l parameter means - link to a specific library. See GCC manual for more information
Thus -lpthread means link to libpthread.so (or pthread.a)
Likewise for -lm -lrt, -lc
[lib]pthread[.so] - POSIX threads
[lib]m[.so] - math standard library (sin, cos, e.t.c.)
[lib]rt[.so] - POSIX realtime extensions
[lib]c[.so] - libc (standard C library)
Each of your .c files are compiled to .o object file (these are called compilation units) and are linked together with the above mentioned libraries.
You are right about how command line parameters should be passed.
|
2,861,478 | 2,894,927 | 2d HUD not drawing properly over QGLWidget (using QPainter) | I am trying to display HUD over my 3D game. For starters, I am just trying to display "Hello World", but I haven't had any success yet! The scene freezes / flickers once I am done.
I am using Qt/C++ and QGLWdiget / QPainter to get this done. I have used overpainting example as my reference to get started. Here is what I do:
override paintEvent(...) in my own subclassed GameGL Class ( GameGL : public QGLWidget )
Push openGL ModelView matrix as the current matrix
enable parameters as gl_depth_test
render my game (:: paintGL1() )
disable the modelview parameters
pop modelview matrix
Make QPainter object
invoke paint.drawText()
Flush using paint.end()
This is pretty much the same as mentioned in the example. However, when I run this code, it experiences freezing / flickering and is highly un-responsive. Would anyone have any idea as to why this might be happening ? I'd really appreaciate any help.
Code:makeCurrent();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
//Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);//.50f, 1.0f );
//glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
m_pLight->SetupLight(GL_AMBIENT | GL_DIFFUSE | GL_SPECULAR);
glEnableClientState( GL_INDEX_ARRAY );
glEnableClientState( GL_VERTEX_ARRAY );
resizeGL( width(), height() );
paintGL1();
//glShadeModel(GL_FLAT);
glDisable(GL_DEPTH_TEST);
//glDisable(GL_CULL_FACE);
glDisable(GL_LIGHTING);
glDisableClientState( GL_INDEX_ARRAY );
glDisableClientState( GL_VERTEX_ARRAY );
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawText(100, 50, QString("Hello"));
painter.end();
Thank you
| For anyone who is still struggling with this and came across this post: here is how I solved it::
Please follow the overpainting example as is. If you look over at the code in the example, you would notice in the constructor, a timer timeout() SIGNAL is connected to animate() SLOT. If you look closely at the animate() slot, it in-turn calls update() a.k.a GLWidget::update(). If you follow the documentation for GLWidget::update(); this in-turn calls paintEvent(...).
This background is important and was the missing piece to my problem. I was earlier using paintGL(...) to draw my scene since I had overriden GLWidget. To support animation or updates to my scene, I had connected the timer to updateGL(). This was in-turn invoking paintGL() via glDraw(). This was the root cause of all the problems.
The code as I had written was calling paintGL() again and again. Following overpainting example, I got rid of paintGL method completely and switched to paintEvent(...) rendering methodology instead. Thus, to keep things in-sync, I had to call update() (instead of updateGL() ) to make things work. The minute I made this transition, things started working as expected. (GLWidget::update() calls paintEvent(...) )
I hope it has helped you any bit. If it still doesn't work for you or need firther explanaition, leave me a comment here and I will try to help.
|
2,861,497 | 2,880,658 | C++ boost function overloaded template | I cannot figure out why this segment gives unresolved overloaded function error (gcc version 4.3.4 (Debian 4.3.4-6)):
#include <algorithm>
#include <boost/function.hpp>
// this does not work
int main1()
{
typedef boost::function<const int&(const int&, const int&)> max;
max m(&std::max<int>);
}
// this does not work
int main2() {
typedef boost::function2<const int&, const int&, const int&> max;
max m(static_cast<max>(&std::max<int>));
}
can you help me, thanks
test.cpp: In function âint main()â:
test.cpp:7: error: no matching function for call to âboost::function2<const int&, const int&, const int&>::function2(<unresolved overloaded function type>)â
/usr/include/boost/function/function_template.hpp:747: note: candidates are: boost::function2<R, T1, T2>::function2(const boost::function2<R, T1, T2>&) [with R = const int&, T0 = const int&\
, T1 = const int&]
/usr/include/boost/function/function_template.hpp:739: note: boost::function2<R, T1, T2>::function2(boost::function2<R, T1, T2>::clear_type*) [with R = const int&, T0 = cons\
t int&, T1 = const int&]
/usr/include/boost/function/function_template.hpp:707: note: boost::function2<R, T1, T2>::function2() [with R = const int&, T0 = const int&, T1 = const int&]
max/min is defined as
template<typename _Tp>
inline const _Tp&
max(const _Tp& __a, const _Tp& __b)
{
// concept requirements
__glibcxx_function_requires(_LessThanComparableConcept<_Tp>)
//return __a < __b ? __b : __a;
if (__a < __b)
return __b;
return __a;
}
I have tried all sorts of template explicit instantiation but nothing seems to work. Same problem appears with g++ 4.1 but not with ICC
this works
#include <algorithm>
#include <boost/function.hpp>
namespace std_ {
template<typename _Tp>
inline const _Tp&
max(const _Tp& __a, const _Tp& __b)
{
// concept requirements
//return __a < __b ? __b : __a;
if (__a < __b)
return __b;
return __a;
}
}
int main()
{
typedef const int &T;
typedef boost::function<T(T,T)> min_;
//typedef const int&(*min_)(const int&, const int&);
min_ m(::std_::max<int>);
}
and this
#include <algorithm>
#include <boost/function.hpp>
int main()
{
//typedef const int &T;
//typedef boost::function<T(T,T)> min_;
typedef const int&(*min_)(const int&, const int&);
min_ m(::std::max<int>);
}
| Update: this is a gcc bug that has been fixed in gcc >=4.4. bugzilla. Also, revised my answer with a reduced test case.
There are two components to this problem: the way boost::function adopts a function pointer and the gcc bug.
boost::function - There is something strange about the error message you listed in the question; there is no candidate constructor that accepts anything like a function address. Digging into the boost::function src, the relevant constructor is (leaving out the enable_if argument):
template<typename Functor>
function(Functor f) : base_type(f) {}
So boost::function doesn't help you out at all in specifying the type of a function pointer; if the function is overloaded the address must be cast to specify its type. If an overloaded function address is used, the above template can't be instantiated, and therefore the appropriate constructor doesn't show up in the error message.
gcc bug - If you look at the stl_algobase.h header again, you'll see there are two templates named max, a two param version and a one param version. This shouldn't be a problem with you code though, right? The term &max<int> should instantiate the single param version and take its address. However, that is not what happens. You can see the problem in the reduced (no header) test case:
template <class T>
const T& max(const T& x, const T& y){
return x > y ? x : y;
}
template <class T, class C>
const T& max(const T& x, const T& y, C comp){
return comp(x, y) ? y : x;
}
template <class R, class A0, class A1>
struct functor{
template <class F>
functor(F f) : f(f) {}
R (*f)(A0, A1);
};
int main(void){
functor<const int&, const int&, const int&> func(&max<int>);
return 0;
}
The above code results in a unresolved overloaded function type with gcc 4.3.4. The fix is either to remove the template <class T, class C> max(...){...} definition or add a static_cast<const int& (*)(const int&, const int&)>(...) around the function address. I'm guessing the problem has to do with incorrect application of partial explicit parameter specification, which is specified by the standard. It lets you leave out trailing template parameters to do things like specify a return value type and not the argument types. That is, the compiler instantiates both template when it should only instantiate the fully specified template. Its moot speculation though, since the bug has been fixed in gcc >= 4.4.
Since one shouldn't hack at stl_algobase.h ;) , the work around Vicente suggests is the correct one, namely cast the function pointer to the desired function pointer type const int& (*)(const int&, const int&). In your code, the cast doesn't work because, as GMan points out, you are casting to a boost::function<...>, which does nothing to resolve the function pointer ambiguity.
|
2,861,523 | 2,865,124 | boost.asio's socket's receive/send functions are bad? |
Data may be read from or written to a
connected TCP socket using the
receive(), async_receive(), send() or
async_send() member functions.
However, as these could result in
short writes or reads, an application
will typically use the following
operations instead: read(),
async_read(), write() and
async_write().
I don't really understand that remark as read(), async_read(), write() and async_write() can also end up in short writes or reads, right?
Why are those functions not the same?
Should I use them at all?
Can someone clarify that remark for me?
| The read, async_read, write, and async_write are composed functions that call the class functions multiple times until the requested number of bytes is transmitted. They are included by the library as a convenience. Otherwise, every developer would need to implement the same logic.
The class functions wrap the underlying OS functions directly, which basically state in the documentation: these functions may return before all of the bytes are transmitted.
In most cases, you should use the free (composed) functions to transmit data.
|
2,861,532 | 2,861,557 | Infrequent segmentation fault in accessing boost::unordered_multimap or struct | I'm having trouble debugging a segmentation fault. I'd appreciate tips on how to go about narrowing in on the problem.
The error appears when an iterator tries to access an element of a struct Infection, defined as:
struct Infection {
public:
explicit Infection( double it, double rt ) : infT( it ), recT( rt ) {}
double infT; // infection start time
double recT; // scheduled recovery time
};
These structs are kept in a special structure, InfectionMap:
typedef boost::unordered_multimap< int, Infection > InfectionMap;
Every member of class Host has an InfectionMap carriage. Recovery times and associated host identifiers are kept in a priority queue. When a scheduled recovery event arises in the simulation for a particular strain s in a particular host, the program searches through carriage of that host to find the Infection whose recT matches the recovery time (double recoverTime). (For reasons that aren't worth going into, it's not as expedient for me to use recT as the key to InfectionMap; the strain s is more useful, and coinfections with the same strain are possible.)
assert( carriage.size() > 0 );
pair<InfectionMap::iterator,InfectionMap::iterator> ret = carriage.equal_range( s );
InfectionMap::iterator it;
for ( it = ret.first; it != ret.second; it++ ) {
if ( ((*it).second).recT == recoverTime ) { // produces seg fault
carriage.erase( it );
}
}
I get a "Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address..." on the line specified above. The recoverTime is fine, and the assert(...) in the code is not tripped.
As I said, this seg fault appears 'randomly' after thousands of successful recovery events.
How would you go about figuring out what's going on? I'd love ideas about what could be wrong and how I can further investigate the problem.
Update
I added a new assert and a check just inside the for loop:
assert( carriage.size() > 0 );
assert( carriage.count( s ) > 0 );
pair<InfectionMap::iterator,InfectionMap::iterator> ret = carriage.equal_range( s );
InfectionMap::iterator it;
cout << "carriage.count(" << s << ")=" << carriage.count(s) << endl;
for ( it = ret.first; it != ret.second; it++ ) {
cout << "(*it).first=" << (*it).first << endl; // error here
if ( ((*it).second).recT == recoverTime ) {
carriage.erase( it );
}
}
The EXC_BAD_ACCESS error now appears at the (*it).first call, again after many thousands of successful recoveries. Can anyone give me tips on how to figure out how this problem arises? I'm trying to use gdb. Frame 0 from the backtrace reads
"#0 0x0000000100001d50 in Host::recover (this=0x100530d80, s=0, recoverTime=635.91148029170529) at Host.cpp:317"
I'm not sure what useful information I can extract here.
Update 2
I added a break; after the carriage.erase(it). This works.
| Correct me if I'm wrong but I would bet that erasing an item in an unordered multimap invalidates all iterators pointing into it. Try "it = carriage.erase(it)". You'll have to do something about ret as well.
Update in reply to your latest update:
The reason breaking out of the loop after calling "carriage.erase(it)" fixed the bug is because you stopped trying to access an erased iterator.
|
2,861,761 | 2,862,023 | Is it good practice to separate code into blocks? | If I have a method that does multiple, related things, is it good practice to stick each "thing" that the method does into a seperate block?
Ex.
{
int var
//Code
}
{
int var
//More Code
}
It would help reduce the number of local variables, and make the code more readable, but I'm not sure if it's a good idea.
| Well, it's certainly good practice to restrict the scope of variables as much as possible. They're less likely to be re-used unnecessarily, and you're more likely to define them when you declare them, which avoids bugs due to undefined variables and such. There are also plenty of cases where you have an object which does something while it's constructed and when it's destroyed, and you want to scope that (for instance, the hour glass in MFC is displayed while its object exists and disappears when it's destroyed in MFC; objects for locking and unlocking mutexes are another good example), and in such cases, scoping the variables with braces makes good sense. So, there are plenty of cases where it makes good sense to create blocks of code specifically to scope variables.
However, there are some problems with doing this heavily.
It can become hard to read if you have a lot of code blocks within a function.
If you try too hard to scope variables as tightly as possible, you run into issues with having to declare variables which need larger scoping earlier than you would otherwise and aren't always able to define them when declaring them.
Functions often express what you're trying to do far better.
So, using extra braces to scope variables can be good practice (reducing the scope of variables as much as reasonably possible certainly is), but in many cases, it's far better to break up your code into multiple functions. Code can be far easier to understand when you have named functions than arbitrary blocks of code. So, if you're in a position where you're looking to declare very many separate blocks of code within a function, consider breaking it up into multiple functions - this is especially true if each of those blocks is directly within the function rather than nested further. So, cases of
T func(...)
{
{
...
}
{
...
}
}
would likely be better broken into multiple functions than separate blocks.
There are certainly times when separate blocks can be good and useful, but generally separate functions would be better.
|
2,861,839 | 2,861,859 | Can the template parameters of a constructor be explicitly specified? | A constructor of a class can be a template function. At the point where such a constructor is called, the compiler usually looks at the arguments given to the constructor and determines the used template parameters from them. Is there also some syntax to specify the template parameters explicitly?
A contrived example:
struct A {
template<typename T>
A() {}
};
Is there a way to instantiate this class? What is the syntax to explicitly specify the constructor's template parameters?
My use case would be a problem were the compiler doesn't seem to find the correct templated constructor. Explicitly specifying the template parameters would probably generate more useful error messages or even resolve the problem.
| No. The C++03 standard says:
[Note: because the explicit template argument list follows the function template name, and
because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.] (§14.5.2/5)
|
2,862,105 | 2,862,113 | A question on vectors, pointers and iterators | Guys, I have a midterm examination tomorrow, and I was looking over the sample paper, and I'm not sure about this question. Any help would be appreciated.
Let v be a vector<Thingie*>, so that each element v[i] contains a pointer to a Thingie. If p is a vector<Thingie*>::iterator, answer the following questions:
what type is p?
what type is *p?
what code provides the address of the actual Thingie?
what code provides the actual Thingie?
|
what type is p?
p is of type vector<Thingie*>::iterator, whatever type that happens to be.
what type is *p?
*p is a Thingie*&; that is, it is a reference to the element in the vector at which the iterator points.
what code provides the address of the actual Thingie?
*p, since the elements of the vector are pointers to the Thingies, and *p gives a reference to the element in the vector.
what code provides the actual Thingie?
**p; that is, you dereference the pointer obtained by *p to obtain the referent of the pointer.
|
2,862,195 | 2,862,290 | Idiomatic use of auto_ptr to transfer ownership to a container | I'm refreshing my C++ knowledge after not having used it in anger for a number of years. In writing some code to implement some data structure for practice, I wanted to make sure that my code was exception safe. So I've tried to use std::auto_ptrs in what I think is an appropriate way. Simplifying somewhat, this is what I have:
class Tree
{
public:
~Tree() { /* delete all Node*s in the tree */ }
void insert(const string& to_insert);
...
private:
struct Node {
...
vector<Node*> m_children;
};
Node* m_root;
};
template<T>
void push_back(vector<T*>& v, auto_ptr<T> x)
{
v.push_back(x.get());
x.release();
}
void Tree::insert(const string& to_insert)
{
Node* n = ...; // find where to insert the new node
...
push_back(n->m_children, auto_ptr<Node>(new Node(to_insert));
...
}
So I'm wrapping the function that would put the pointer into the container, vector::push_back, and relying on the by-value auto_ptr argument to
ensure that the Node* is deleted if the vector resize fails.
Is this an idiomatic use of auto_ptr to save a bit of boilerplate in my
Tree::insert? Any improvements you can suggest? Otherwise I'd have to have
something like:
Node* n = ...; // find where to insert the new node
auto_ptr<Node> new_node(new Node(to_insert));
n->m_children.push_back(new_node.get());
new_node.release();
which kind of clutters up what would have been a single line of code if I wasn't
worrying about exception safety and a memory leak.
(Actually I was wondering if I could post my whole code sample (about 300 lines) and ask people to critique it for idiomatic C++ usage in general, but I'm not sure whether that kind of question is appropriate on stackoverflow.)
| It is not idiomatic to write your own container: it is rather exceptional, and for the most part useful only for learning how to write containers. At any rate, it is most certainly not idiomatic to use std::autp_ptr with standard containers. In fact, it's wrong, because copies of std::auto_ptr aren't equivalent: only one auto_ptr owns a pointee at any given time.
As for idiomatic use of std::auto_ptr, you should always name your auto_ptr on construction:
int wtv() { /* ... */ }
void trp(std::auto_ptr<int> p, int i) { /* ... */ }
void safe() {
std::auto_ptr<int> p(new int(12));
trp(p, wtv());
}
void danger() {
trp(std::auto_ptr<int>(new int(12)), wtv());
}
Because the C++ standard allows arguments to evaluate in any arbitrary order, the call to danger() is unsafe. In the call to trp() in danger(), the compiler may allocate the integer, then create the auto_ptr, and finally call wtv(). Or, the compiler may allocate a new integer, call wtv(), and finally create the auto_ptr. If wtv() throws an exception then danger() may or may not leak.
In the case of safe(), however, because the auto_ptr is constructed a-priori, RAII guarantees it will clean up properly whether or not wtv() throws an exception.
|
2,862,236 | 2,862,436 | STL member variable initalization issue with windows API | I am creating a windows app that uses a vector of stings as a member variable. For some reason, I can compile but when it tries to get at any of the vectors members is crashes. the error is 0xC0000005: Access violation reading location 0xcdcdcdd9. in the member function of the vector class.
this is the size() function where it breaks.
size_type capacity() const
{ // return current length of allocated storage
return (this->_Myend - this->_Myfirst);
}
I am using visual studios 2010.
thank you
Django
| I've come across this kind of thing before. Most likely cause is a corrupt heap.
|
2,862,242 | 2,862,250 | Casting problem cant convert from void to float C++ | as i said i get this horrible error i dont really know what to do anymore
float n= xAxis[i].Normalize();
thats where i get the error and i get it cuz normalize is a void function this is it
void CVector::normalize()
{
float len=Magnitude();
this->x /= len;
this->y /= len;
}
i need normalize to stay as void tho i tried normal casting like this
float n= (float)xAxis[i].Normalize();
and it doesnt work also with static,dynamic cast,reinterpret,const cast and cant make it work any help would be really apreciated...
thank you >.<
| A void function doesn't return anything, so there's nothing to assign to n.
You should return some value from normalize to assign it to n.
float CVector::normalize()
{
float len=Magnitude();
this->x /= len;
this->y /= len;
return 10.0;
}
|
2,862,284 | 2,862,316 | Returning a C++ reference in a const member functions | A have a class hierarchy that looks somethign like this:
class AbstractDataType {
public:
virtual int getInfo() = 0;
};
class DataType: public AbstractDataType {
public:
virtual int getInfo() { };
};
class Accessor {
DataType data;
public:
const AbstractDataType& getData() const {
return(data);
}
};
Well, GCC 4.4 reports:
In member function ‘const AbstractDataType& Accessor::getData() const’:
error: invalid initialization of reference of type ‘const AbstractDataType&’ from expression of type ‘const DataType’
Where am I going wrong - is this a case where I MUST use a pointer?
[edit - fixed semi-colons]
| No you do not need to use a pointer. You can use a reference or a pointer equally in this case.
The code you pasted should work and does work in g++ 4.4 and Visual Studio 2010.... other than the missing semicolons after the class declarations.
I'm guessing maybe your code here doesn't match exactly the code you are compiling.
In particular did you accidentally do this in code?
class DataType /*: public AbstractDataType*/ {
public:
virtual int getInfo() { };
};
|
2,862,346 | 2,862,369 | Storing header and data sections in a CSV file | This should be relatively easy to do, but after several hours straight programming my mind seems a bit frazzled and could do with some help.
I have a C++ class which I am currently using to store read/write data to file. I was initially using binary data, but have decided to store the data as CSV in order to let programs written in other languages be able to load the data.
The C++ class looks a bit like this:
class BinaryData
{
public:
BinaryData();
void serialize(std::ostream& output) const;
void deserialize(std::istream& input);
private:
Header m_hdr;
std::vector<Row> m_rows;
};
I am simply rewriting the serialize/deserialize methods to write to a CSV file. I am not sure on the "best" way to store a header section and a "data" section in a "flat" CSV file though - any suggestions on the most sensible way to do this?
| The most sensible way is don't do it. Let an existing library do it for you. You'll never be able to put the requisite amount of work into this class that you'll need to maintain backwards compatibility and changing requirements.
Use an existing solution, like Google's protocol buffers. They're stored in binary - so you get the size benefit, and there are many language bindings available. In addition, you can get human readable field-based ascii representations trivially.
|
2,862,398 | 2,869,379 | SWIG-Lua question on class returning another class | I am concreting a question I had earlier.
I have two classes in C++ and I use SWIG to wrap them. A method in one class can return a pointer to the other class. How can I get Lua to see it as more than just a userdata?
More concretely:
I have
class fruit
{
int numberofseeds;
//some other stuff about fruit constructors etc...
public:
getseedcount()
{
return numberofseeds;
}
}
class tree
{
fruit * apple;
public:
//constructors and whatnot
fruit * getfruit()
{
return apple;
}
}
I wrap these two class with SWIG so I can access them in Lua
So I can get in Lua the object x=pomona.tree(grannysmith).
My question now is: How can I arrange for things so that when I type y=x:getfruit() I will get a pomona:fruit type object? Where I can write something line y:getseedcount()?
At the moment all I get is userdata which not edible.
| If your SWIG .i file is set up correctly, you can use the ":" operator:
local y = x:getfruit()
local z = y:getseedcount()
See the "Classes" section (23.2.7) of the SWIG Lua documentation.
If that doesn't work you need to tell SWIG how to convert a fruit* out parameter to a Lua representation using a typemap in your .i file. Something like:
%typemap(out) fruit*
{
swig_module_info* module = SWIG_GetModule(L);
swig_type_info* typeInfo = SWIG_TypeQueryModule(module, module, "fruit *");
SWIG_NewPointerObj(L, $1, typeInfo, 1);
}
|
2,862,454 | 2,862,476 | what is the reason of Invalid Address specified to RtlFreeHeap | the develop environment is vs2008, the language is c++, when I release the problem,at beginning it run with out problem but after several minutes it stop and show error like that : HEAP[guessModel.exe]: Invalid Address specified to RtlFreeHeap( 003E0000, 7D7C737B ).
who can tell me the reason of the error. thank you very much.
| My guess is that you are trying to use the wild pointer. Either the pointer to the memory which got freed has been de-referenced or some invalid pointer has been passed to free function.
It is very hard to tell the reason without seeing the actual code. You can attach some debugging tools like WinDbg and get the cause for this error.
|
2,862,462 | 2,866,548 | I have a BrowserHelperObject(BHO) in c++ and i need to block some keyboard controls (Ctrl-o) in a i-frame | I need to know of a way to prevent the user to 'open a new url' (with Ctrl + O) as soon as he has the focus on my sidebar (right-sided iframe).
In fact, my sidebar offers some controls and the user should not be able to 'navigate' to other website through the sidebar.
I'm using a bho in C++ using ATL(active template library), but maybe if anyone knows of a simplier way like in JS(javascript) or PHP(Hypertext Preprocessor) ? All ideas are appreciated.
| Implement IInputObject and pay special attention to HasFocusIO.
|
2,862,562 | 2,862,588 | Path String Concatenation Question | Please see my code below.
ifstream myLibFile ("libs//%s" , line); // Compile failed here ???
I want to combine the path string and open the related file again.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("libs//Config.txt");
// There are several file names listed in the COnfig.txt file line by line.
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
// Read details lib files based on the each line file name.
string libFileLine;
ifstream myLibFile ("libs//%s" , line); // Compile failed here ???
if (myLibFile.is_open())
{
while (! myLibFile.eof() )
{
cout<< "success\n";
}
myLibFile.close();
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Assume my [Config.txt] include the content below. And all the *.txt files located in libs folder.
file1.txt
file2.txt
file3.txt
| The ifstream constructor does not work that way. Its first parameter is a C string to the file you want to open. Its second parameter is an optional set of mode flags.
If you want to concatenate the two strings, just concatenate the two strings:
std::string myLibFileName = "libs/" + line;
ifstream myLibFile(myLibFileName.c_str());
// Or, in one line:
ifstream myLibFile(("libs/" + line).c_str());
(the call to c_str() is required because the ifstream constructor takes a const char*, not a std::string)
|
2,862,636 | 2,869,136 | C++: FFMPEG and SDL resources | I'm looking for resources (preferably books, but websites are fine too) for using FFmpeg and/or SDL with C++.
Stuff I'd like to be able to do (eventually):
Decode and play videos in realtime to a QT widget (the QT part isn't a problem)
Overlay text and images on the video (in realtime)
Loop video
Cross-fade from one video to another (in realtime)
Some kind of DVD functionality
LIVE sources? (i.e. webcam, stream, etc.)
So far I've looked at (and consider helpful) the following resources:
FFmpeg and SDL Tutorial by Dranger (extremely helpful)
Stack Overflow: ffmpeg C API documentation/tutorial (not a duplicate, btw)
Sample code bundled with FFMPEG libraries
(I'll try and update this list with anything helpful below)
Thanks for any help...
Also: Operating System is Windows (but maybe one day cross-platform)
Also 2: Resources using alternatives are welcome too... i.e. DirectShow, VFW, etc.
| If all you need is to decode and play videos and require overlays I would consider using the Phonon framework, and use QT Graphics View by using a Phonon::VideoWidget inside a QGraphicsProxyWidget. That way you can easily get overlays, cross-fading, animations etc. Phonon in Windows uses DirectShow as a back-end. You can install FFDShow and get the same codecs ffmpeg has to play videos.
|
2,862,852 | 2,862,879 | Returning reference to object is not changing the address in c++ | I am trying to understand functions returning a reference. For that I have written a simple program:
#include<iostream>
using namespace std;
class test
{
int i;
friend test& func();
public:
test(int j){i=j;}
void show(){cout<<i<<endl;}
};
test& func()
{
test temp(10);
return temp; //// Address of temp=0xbfcb2874
}
int main()
{
test obj1(50); // Address of obj1=0xbfcb28a0
func()=obj1; <= Problem:The address of obj1 is not changing
obj1.show(); // // Address of obj1=0xbfcb28a0
return 0;
}
I ran the program using gdb and observed that the address of obj1 still remains same, but I expect it to get changed to 0xbfcb2874. I am not clear with the concept. Please help.
| There are several problems in your code:
(1) That is not how you want to return a reference. temp(10) is an automatic (i.e. resides in stack) variable and will be destroyed once your program goes out of scope of the test function. A better way to show this would be to return a reference to a variable passed (e.g. for chaining of calls):
Test& func(Test& some_param) {
// Do something with some_param...
// Return it as a reference.
return some_param;
}
(2) You are assigning the value of obj1 to func(), while what you want would be to assign the return value of func() to a variable. Try this:
Test obj1(50);
Test& obj2 = func(obj1); // Address of obj2 should now be the same as obj1.
(3) func() need not be a friend of Test. In fact, it should not. A friend class/functions allow the class/functions to access private members of Test. That is not what you want to do too often.
|
2,862,875 | 2,862,944 | C++ overloading virtual = operator | here is the code for my question:
class ICommon
{
public:
virtual ICommon& operator=(const ICommon & p)const=0;
};
class CSpecial : public ICommon
{
public:
CSpecial& operator=(const CSpecial & cs)const
{
//custom operations
return *this;
}
};
CSpecial obj;
Basically: I want the interface ICommon to force it's descendants to implement = operator but don't want to have any typecasts in the implementation. The compiler says "can't instantiate an abstract class.
Any help/advice will be appreciated.
| To echo what Naveen said, the operator=() defined in CSpecial isn't compatible with the one defined in ICommon, and results in an overload rather than an override. While you can have covariant return types (as you've done), the arguments themselves can't be covariant.
Furthermore, you've defined the ICommon::operator=() as const, which seems counterintuitive. In the derived class, you've made it non-const (as expected), but again, this makes the function signatures further incompatible.
Naveen's clone() idea is probably your best bet. Otherwise, you can pass an ICommon const reference to your CSpecial operator=() and attempt some dynamic_cast<>() magic internally, but that smells funny.
Good luck!
|
2,862,915 | 2,863,634 | C++ CRTP(template pattern) question | following piece of code does not compile, the problem is in T::rank not be inaccessible (I think) or uninitialized in parent template.
Can you tell me exactly what the problem is?
is passing rank explicitly the only way? or is there a way to query tensor class directly?
Thank you
#include <boost/utility/enable_if.hpp>
template<class T, // size_t N,
class enable = void>
struct tensor_operator;
// template<class T, size_t N>
template<class T>
struct tensor_operator<T, typename boost::enable_if_c< T::rank == 4>::type > {
tensor_operator(T &tensor) : tensor_(tensor) {}
T& operator()(int i,int j,int k,int l) {
return tensor_.layout.element_at(i, j, k, l);
}
T &tensor_;
};
template<size_t N, typename T = double>
// struct tensor : tensor_operator<tensor<N,T>, N> {
struct tensor : tensor_operator<tensor<N,T> > {
static const size_t rank = N;
};
tensor <4> D; // compiler attempts to instantiate undefined template, not specialization
I know the workaround, however am interested in mechanics of template instantiation for self-education
| In CRTP the base class template take advantage of the fact that member function bodies (definitions) are not instantiated until long after their declarations. In your code the base class depends on incomplete type.
|
2,862,993 | 2,863,313 | iPhone/iPad C++ Example | Does anyone know where or how to obtain a C++ example to create iPhone apps? What I am looking for is just using C++ (no objective-C or just the bare essential objective-C) and no interface builder, source only.
Can ayone help me locate such a beast?
| You can download Carmack's source for Wolfenstein3D for the iphone to see what a program that only uses the minimum of Objective-C necessary to run looks like.
He uses C mixed with Objective-C in this case ,but as everyone has mentioned, there's no way to avoid using some Objective-C if you plan on linking against the iPhone SDK.
|
2,863,347 | 2,863,360 | Declaring the array size with a non-constant variable | I always thought that when declaring an array in C++, the size has to be a constant integer value.
For instance:
int MyArray[5]; // correct
or
const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct
but
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect
Here is also what is explained in The C++ Programming Language, by Bjarne Stroustrup:
The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a vector(§3.7.1, §16.3). For example:
void f(int i) {
int v1[i]; // error : array size not a constant expression
vector<int> v2(i); // ok
}
But to my big surprise, the code above does compile fine on my system!
Here is what I tried to compile using GCC v4.4.0:
void f(int i) {
int v2[i];
}
int main() {
int i = 3;
int v1[i];
f(5);
}
Success?!?
Is there something I'm missing?
| This is a GCC extension to the standard:
You can use the -pedantic option to cause GCC to issue a warning, or -std=c++98 to make in an error, when you use one of these extensions (in case portability is a concern).
|
2,863,420 | 2,863,440 | Error in VC++ for code that looks perfectly good C++? | Hey guys. Check out this piece of sample code.
#include "stdafx.h"
#include<conio.h>
#include<string.h>
class person{
private char name[20];
private int age;
public void setValues(char n[],int a)
{
strcpy(this->name,n);
this->age=a;
}
public void display()
{
printf("\nName = %s",name);
printf("\nAge = %d",age);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
person p;
p.setValues("ram",20);
p.display();
getch();
return 0;
}
I am getting the following errors :
1>------ Build started: Project: first, Configuration: Debug Win32 ------
1> first.cpp
1>c:\documents and settings\dark wraith\my documents\visual studio 2010\projects\first\first\first.cpp(9): error C2144: syntax error : 'char' should be preceded by ':'
1>c:\documents and settings\dark wraith\my documents\visual studio 2010\projects\first\first\first.cpp(10): error C2144: syntax error : 'int' should be preceded by ':'
1>c:\documents and settings\dark wraith\my documents\visual studio 2010\projects\first\first\first.cpp(12): error C2144: syntax error : 'void' should be preceded by ':'
1>c:\documents and settings\dark wraith\my documents\visual studio 2010\projects\first\first\first.cpp(17): error C2144: syntax error : 'void' should be preceded by ':'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
| The syntax of declaring public and private is wrong. Unlike other languages, in C++ it should be
class person{
private:
char name[20];
int age;
public:
void display();
....
|
2,863,450 | 2,863,841 | C++ console output in Netbeans | When I run a C++ program in Netbeans on a Mac that has cout or printf statements the output is displayed in a terminal opened using X11. Is there a console built into Netbeans? If yes, how do I change the output to it?
Thanks,
Spencer
| Under Project Properties -> Run -> Console Type you can choose "Output Window" instead of External Terminal.
|
2,863,519 | 2,863,546 | Arena in Malloc Function | I am using malloc_stats() to print malloc related statistics in which I am finding "Arena 0" for some programs and "Arena 0 and Arena 1" for some other programs.
What do these arenas represent?
| See link text. It looks like heap is a collection of arenas ("sub-heaps") to handle memory allocation between several threads, thus reducing contention.
|
2,863,836 | 2,863,921 | Do Java programs ever crash? | I am a c++ programmer , I know little bit about java. I know that java programmers do not have to work with memory directly like C++. I also know that most crashes in C++ appliations are due to memory corruptions.
So can an application written in Java crash due to a memory related issue?
Thanks
| Contrary to some other answers I’ll claim that Java programs will crash as often, or possibly even more often than C++ programs.
By “crash” most people understand that a program encounters an error that isn’t properly handled, causing the application to terminate. Well, this of course happens and has got nothing to do with the way Java treats memory.
This is a good thing. What makes C++ so dangerous, and Java comparatively safe, is the precisely the fact that Java will crash in cases where C++ will happily continue running, albeit doing very wrong and potentially dangerous things (such as writing to uninitialized memory, overflowing buffers, …). Java’s crashing (e.g. throwing exceptions) prevents worse damage. C++ applications, on the other hand (due to the failure to terminate on errors), may do damage to external data or the system. Or they may just deliver a wrong (but seemingly plausible) result.
It’s against these dangers that Java guards, not against crashes per se.
|
2,864,004 | 2,864,020 | C++ Basic Class Layout | Learning C++ and see the class laid out like this:
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
I know Java and methods(functions) in Java are written within the class. The class looks like a Java interface. I know I can write the class like this:
class CRectangle {
int x, y;
public:
void set_values (int a, int b) {
x = a;
y = b;
};
int area () {return (x*y);}
};
But is there a difference or standard?
| There's a difference. When you write the definition of the function within the class definition (case 2), then the function is considered to have been declared inline. This is standard C++.
Usage, is to declare the member functions (Java methods) within the class definition, in a header file (.h), and to define these member functions in a C++ file (.cpp, .cc, or .C, …) This reduces compilation time, when you change the body of a function, only the C++ file has to be compiled, whereas if you change something in the header file, all C++ files that include this header are to be compiled.
|
2,864,058 | 2,864,123 | Custom iterator which converts values before saving it | A typical forward iterator is expected to implement following methods:
value_type& operator*();
value_type* operator->();
I'm writing a custom iterator for a custom container where user expects to see a value_type different from representation of the value inside a container. So when returning a value_type value to user I convert it from inner representation to user-expected value_type. It is easy to implement inside mentioned members.
Could you advice how to handle l-values? Where can I handle conversion of value_type to inner representation when user assigns values to iterator in syntax like *it = value_type(5)?
I thought of returning a functor but I dislike this idea becaues of non-usual syntax on caller's side.
| You might want to take a look into the implementation of the std::vector<bool> specialization iterators, as they tackle the same problem. Note that with time, the specialization has been frown upon mainly because it does not comply with the container requirements (the iterators don't provide references to the actual contained type, but a proxy value), and that will also be a problem with your implementation.
The other possible approach is using a regular container but having the stored type accept implement the assignment/conversions to and from the user expected types. If that is not possible with your current stored type, you can write a wrapper for it.
A simplified wrapper (you will need to work on it to make it work):
template <typename T, typename U>
class wrapper
{
public:
typedef T store_type;
typedef U value_type;
wrapper() : stored() {}
wrapper( value_type const & v )
: stored( convert<store_type>(v) {}
wrapper& operator=( value_type const & value ) { // or pass-by-value
stored = convert<store_type>(value); // or however you can convert them
return *this;
}
operator value_type() const { // I don't quite like this, if possible use explicit conversions
return convert<value_type>(stored);
}
private:
store_type stored; // maybe storage is handled externally and this can be pointer/ref.
};
// For the simple test double<->int conversion static cast suffices
template <typename T, typename U>
T convert( U in ) {
return static_cast<T>(in);
}
int main() {
std::vector< wrapper<double,int> > v;
v.push_back( 10 );
int x = v[0];
v[0] = 5;
std::vector< wrapper<int,double> > v2;
v.push_back( 10.5 );
double y = v2[0];
v2[0] = 11.3;
}
|
2,864,066 | 2,864,462 | Determine if the current thread has low I/O priority | if (reader.is_lazy()) goto tldr;
I have a background thread that does some I/O-intensive background type work. To please the other threads and processes running, I set the thread priority to "background mode" using SetThreadPriority, like this:
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
However, THREAD_MODE_BACKGROUND_BEGIN is only available in Windows Server 2008 or newer, as well as Windows Vista and newer, but the program needs to work well on Windows Server 2003 and XP as well. So the real code is more like this:
if (!SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)) {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
}
The problem with this is that on Windows XP it will totally disrupt the system by using too much I/O. I have a plan for an ugly and shameful way of mitigating this problem, but that depends on me being able to determine if the current thread has low I/O priority or not.
Now, I know I can store which thread priority I ended up setting, but the control flow in the program is not really well suited for this. I would rather like to be able to test later whether or not the current thread has low I/O priority -- if it is in "background mode".
tldr:
GetThreadPriority does not seem to give me this information, it only gives the CPU priority.
Is there any way to determine if the current thread has low I/O priority?
| Well it fails if you've already set it to background mode. Could you, dependent on whether you would like it to be background processing, not just Set the priority to background begin and see if it fails?
If you'd expect/want it not to be then you could test by calling background end.
If thats not good to you you'd probably be best off just using Thread Local Storage to store whether it is in background mode or not.
Edit by Magnus Hoff: This is how I ended up implementing it:
bool has_low_io_priority() {
if (SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN)) {
// Seems we were able to enter background mode. That means we were
// not in background mode from before.
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
return false;
} else {
DWORD err = GetLastError();
if (err == ERROR_THREAD_MODE_ALREADY_BACKGROUND) return true;
else return false; //< Background mode is not available at all
}
}
Works well :)
|
2,864,306 | 2,864,809 | How to reverse PNG for drawing | I make game Mario and I want when I use left key < , the character will turn his head to left :-?
How can I implement that ? Thanks for reading this :)
| BitMap::RotateFlip(RotateNoneFlipY)
|
2,864,307 | 2,864,326 | Can't I send NULL as a parameter with a constructor? | Lets say i have a Shape object that has a constructor like this:
Shape( width, height, radius, depth )
Now, I just have a silly rect so i dont need redius and depth... is it okey to do
Shape myRect(50, 50, NULL, NULL) ?
I know its not the best idea and I should use inheritance and stuff but this is the mess im in so can i use NULL like this?
| Depends on what types radius and depth are. If they are integers, you have to use an out-of-bound value like -1 to indicate "not set" (out-of-bound could also be 0 if you declare it that way). If they are pointers, NULL could be used.
Actually what you describe is a common example of bad inheritance, and it's used in OOP teaching to show why not everything should be inherited. Shapes are just too different for this.
|
2,864,337 | 2,864,745 | What's the purpose of `qt_noop` | I just found the existence of qt_noop() define in the qglobal.h as:
inline void qt_noop() {}
What's the point of it?
| I know it's used internally in some macros that should do something only for debug builds, for example:
# ifndef QT_NO_DEBUG
# define Q_ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop())
# else
# define Q_ASSERT(cond) qt_noop()
# endif
#endif
|
2,864,450 | 2,866,707 | UTC timestamp in millisecond using C++ under Windows | How do I get the UTC time in milliseconds under the Windows platform?
I am using the standard library which give me UTC time in seconds. I want to get the time in milliseconds. Is there a reference of another library which give me the accurate UTC time in milliseconds?
| GetSystemTime() produces a UTC time stamp with millisecond resolution. Accuracy however is far worse, the clock usually updates at 15.625 millisecond intervals on most Windows machines. There isn't much point in chasing improved accuracy, any clock that provides an absolute time stamp is subject to drift. You'd need dedicated hardware, usually a GPS radio clock, to get something better. Which are hard to use properly on a non-realtime multi-tasking operating system. Worst-case latency can be as much as 200 milliseconds.
|
2,864,574 | 2,864,648 | Problem building stripped down version of Qt 4.6.2 | I'm trying to build a smaller version of Qt, I used the following configuration options:
./configure -qt-sql-mysql -no-qt3support -no-audio-backend -no-phonon -no-phonon-backend -no-opengl -no-script -no-scripttools -no-javascript-jit -no-webkit -no-svg -no-multimedia -fast
After executing make, I eventually run into the following error:
make[3]: Entering directory `/opt/qtsdk-2010.02/qt/tools/assistant/tools'
cd assistant/ && make -f Makefile
make[4]: Entering directory `/opt/qtsdk-2010.02/qt/tools/assistant/tools/assistant'
g++ -c -pipe -g -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_SQL_LIB -DQT_XML_LIB -DQT_GUI_LIB
-DQT_NETWORK_LIB -DQT_CORE_LIB -D_LARGEFILE64_SOURCE -D_LARGEFILE_SOURCE -DQT_SHARED
-I../../../../mkspecs/linux-g++ -I. -I../../../../include/QtCore
-I../../../../include/QtNetwork -I../../../../include/QtGui -I../../../../include/QtXml
-I../../../../include/QtSql -I../../../../include -I../../../../include/QtHelp
-I../../../shared/fontpanel -I.moc/release-shared -I.uic/release-shared
-o .obj/release-shared/helpviewer.o helpviewer.cpp
In file included from helpviewer.cpp:42:
helpviewer.h:51:20: error: QWebView: No such file or directory
Any pointers on what is wrong here?
| It is trying to build the Assistant (that is the tool you us to view Qt documentation) tool, the Assistant needs webkit. If you don't need Assistant in your application when you are distributing it, just exclude it from the build
|
2,864,804 | 2,864,824 | Template specialization within template definition: is this supported for all compilers or standard usage? | This compiled on VS 2008, but it seems like non-standard usage of templates.
template <class T>
class Foo
{
public:
void bar(Foo<int> arg)
{
// do some stuff here
}
// more code ...
};
Is there an issue since the template specialization Foo<int> is contained within the definition of its own template class?
| It's not really specialisation - you are just saying that function takes a parameter of type Foo <int> - the fact that the function is itself a member of the Foo class isn't really important. And yes, it's legal.
|
2,865,036 | 2,865,437 | Why can't we overload "=" using friend function? | Why it is not allowed to overload "=" using friend function?
I have written a small program but it is giving error.
class comp
{
int real;
int imaginary;
public:
comp(){real=0; imaginary=0;}
void show(){cout << "Real="<<real<<" Imaginary="<<imaginary<<endl;}
void set(int i,int j){real=i;imaginary=j;}
friend comp operator=(comp &op1,const comp &op2);
};
comp operator=(comp &op1,const comp &op2)
{
op1.imaginary=op2.imaginary;
op1.real=op2.real;
return op1;
}
int main()
{
comp a,b;
a.set(10,20);
b=a;
b.show();
return 0;
}
The compilation gives the following error :-
[root@dogmatix stackoverflow]# g++ prog4.cpp
prog4.cpp:11: error: ‘comp operator=(comp&, const comp&)’ must be a nonstatic member function
prog4.cpp:14: error: ‘comp operator=(comp&, const comp&)’ must be a nonstatic member function
prog4.cpp: In function ‘int main()’:
prog4.cpp:25: error: ambiguous overload for ‘operator=’ in ‘b = a’
prog4.cpp:4: note: candidates are: comp& comp::operator=(const comp&)
prog4.cpp:14: note: comp operator=(comp&, const comp&)
| The assignment operator is explicitly required to be a class member operator. That is a sufficient reason for the compiler to fail to compile your code. Assignment is one of the special member functions defined in the standard (like the copy constructor) that will be generated by the compiler if you do not provide your own.
Unlike other operations that can be understood as external to the left hand side operator, the assignment is an operation that is semantically bound to the left hand side: modify this instance to be equal to the right hand side instance (by some definition of equal), so it makes sense to have it as an operation of the class and not an external operation. On the other hand, other operators as addition are not bound to a particular instance: is a+b an operation of a or b or none of them? -- a and b are used in the operation, but the operation acts on the result value that is returned.
That approach is actually recommended and used: define operator+= (that applies to the instance) as a member function, and then implement operator+ as a free function that operates on the result:
struct example {
example& operator+=( const example& rhs );
};
example operator+( const example& lhs, const example& rhs ) {
example ret( lhs );
ret += rhs;
return ret;
}
// usually implemented as:
// example operator+( example lhs, const example& rhs ) {
// return lhs += rhs; // note that lhs is actually a copy, not the real lhs
//}
|
2,865,396 | 2,865,777 | Bit manipulation, permutate bits | I am trying to make a loop that loops through all different integers where exactly 10 of the last 40 bits are set high, the rest set low. The reason is that I have a map with 40 different values, and I want to sum all different ways ten of these values can be multiplied. (This is just out of curiosity, so it's really the "bitmanip"-loop that is of interest, not the sum as such.)
If I were to do this with e.g. 2 out of 4 bits, it would be easy to set all manually,
0011 = 3,
0101 = 5,
1001 = 9,
0110 = 6,
1010 = 10,
1100 = 12,
but with 10 out of 40 I can't seem to find a method to generate these effectively. I tried, starting with 1023 ( = 1111111111 in binary), finding a good way to manipulate this, but with no success. I've been trying to do this in C++, but it's really the general method(if any) that is of interest. I did some googling, but with little success, if anyone has a good link, that would of course be appreciated too. :)
| A bit more complicated, but done purely by bit manipulation. Your example:
#define WIDTH 4
#define BITS 2
void printbits(long pattern) {
long bit;
for (bit = 1L << WIDTH - 1; bit; bit >>= 1)
putchar(pattern & bit ? 49 : 48);
putchar('\n');
}
void movebits(pattern, bit) {
long mask = 3L << bit;
while (((pattern ^= mask) & mask) && (mask < 1L << WIDTH)) {
mask <<= 1;
printbits(pattern);
if (bit)
movebits(pattern, bit - 1);
}
}
int main() {
long pattern = (1L << BITS) - 1L, mask;
printbits(pattern);
movebits(pattern, BITS - 1);
}
Your real application:
#define WIDTH 40
#define BITS 10
and, as polygenelubricants says, be prepared to wait for bit :) Of course, you will replace printbits with something more useful to you...
(Edited for insufficient testing :/ Damn typos...)
|
2,865,451 | 2,865,554 | Marshalling an array of shorts: "Mismatch has occurred" | I have the following C++ struct:
typedef struct FormulaSyntax{
WORD StructSize;
short formulaSyntax [2];
} FormulaSyntax;
I have a DLL method which takes an instance of this struct. Here's what I've tried on the C# side:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FormulaSyntax {
public short StructSize;
public short[] formulaSyntax;
}
[DllImport(DLL_NAME, EntryPoint = "PEGetFormulaSyntax",
CharSet = CharSet.Unicode)]
public static extern bool getFormulaSyntax(short reportID,
ref FormulaSyntax syntax);
...
FormulaSyntax syntax = new FormulaSyntax();
syntax.formulaSyntax = new short[2];
syntax.StructSize = (short)Marshal.SizeOf(syntax);
PrintEngine.getFormulaSyntax(context.oldApiID, ref syntax);
This crashes, giving me the message
Mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata.
What am I doing wrong?
| Found the answer here: Here is what my C# struct needed to look like - it needed the MarshalAs line. It works now.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FormulaSyntax {
public short StructSize;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I4,
SizeConst = 2)]
public short[] formulaSyntax;
}
|
2,866,048 | 2,866,156 | Who deletes the copied instance in + operator ? (c++) | I searched how to implement + operator properly all over the internet and all the results i found do the following steps :
const MyClass MyClass::operator+(const MyClass &other) const
{
MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this);
result += other; // Use += to add other to the copy.
return result; // All done!
}
I have few questions about this "process" :
Isn't that stupid to implement + operator this way, it calls the assignment operator(which copies the class) in the first line and then the copy constructor in the return (which also copies the class , due to the fact that the return is by value, so it destroys the first copy and creates a new one.. which is frankly not really smart ... )
When i write a=b+c, the b+c part creates a new copy of the class, then the 'a=' part copies the copy to himself.
who deletes the copy that b+c created ?
Is there a better way to implement + operator without coping the class twice, and also without any memory issues ?
thanks in advance
| Under the circumstances, I'd probably consider something like:
MyClass MyClass::operator+(MyClass other) {
other += *this;
return other;
}
Dave Abrahams wrote an article a while back explaining how this works and why this kind of code is usually quite efficient even though it initially seems like it shouldn't be.
Edit (thank you MSalters): Yes, this does assume/depend upon the commutative property holding for MyClass. If a+b != b+a, then the original code is what you want (most of the same reasoning applies).
|
2,866,194 | 2,866,542 | DeferWindowPos and SWP_SHOWWINDOW/SWP_HIDEWINDOW | I am writing a virtual desktop application which utilises the DeferWindowPos API functions. The current method I am using is moving the windows off the screen if they're not on the current virtual desktop. However I know wish to also hide the windows that are off-screen so they do not appear on the task bar. I have attempted this by also passing SWP_SHOWWINDOW/SWP_HIDEWINDOW to the DeferWindowPos() calls. I have read a few sites regarding this and one of them suggested that if SWP_SHOWWINDOW/SWP_HIDEWINDOW are passed, then the window will only show or hide, and no reposition. Can anyone confirm this, or am I doing something wrong?
| In addition to the rtfm, DeferWindowPos is eventually going to call SetWindowPos. SetWindowPos always validates its parameters by passing them to the WindowProc via WM_WINDOWPOSCHANGING so, unless you are also hooking every windows WindowProc as part of your virtual desktop manager, moving them off screen is going to fail for any windows where the devs are doing something "clever" or unusual - like clamping to the edge of the workspace.
|
2,866,307 | 2,866,407 | BYTE typedef in VC++ and windows.h | I am using Visual C++, and I am trying to include a file that uses BYTE (as well as DOUBLE, LPCONTEXT...) , which by default is not a defined type.
If I include windows.h, it works fine, but windows.h also defines GetClassName wich I don't need. I am looking for an alternative to windows.h include, that would work with VC++ and would define most of the types like BYTE, DOUBLE ...
Thanks
| You need to include windows.h to get those types. If you want to reduce the number of defines that windows.h brings in, you can #define WIN32_LEAN_AND_MEAN before including windows.h, which will exclude a lot of stuff (but not everything). See http://support.microsoft.com/kb/166474.
|
2,866,399 | 2,866,415 | Should I 'delete' this CDC? | Folks,
I'm trying to track down an intermittant bug that's showing up on site.
I've a feeling it's in some GDI code I'd to cobble together to get a tally printer working.
I'm connfused over how to delete this CDC, my code looks OK to me, but is this correct.
// Create a device context for printing
CDC* dc = new CDC();
if(! dc->CreateDC(safeDriverName.AsBSTR(), safePrinterName.AsBSTR(), NULL, NULL))
{
throw . . .
}
// as I finish with the CDC
dc->DeleteDC();
delete dc;
Do I need delete dc after dc->DeleteDC();?
Thanks
| Since you allocated dc on the heap, yes you do need to delete dc. Not only that but if you keep the code as you have it you should also have a delete dc before your throw. The DeleteDC function is not related to the allocated memory of dc.
You could simplify to this though:
// Create a device context for printing
CDC dc;
if(! dc.CreateDC(safeDriverName.AsBSTR(), safePrinterName.AsBSTR(), NULL, NULL))
{
throw . . .
}
// as I finish with the CDC
dc.DeleteDC();
Update: As @Fred mentioned, CDC's destructor will call DeleteDC() for you.
|
2,866,539 | 2,866,631 | C++ Header Guard issues | I am making a small C++ framework, which contains many .h and .cpp.
I have created a general include which include all my .h file such as:
framework.h
#include "A.h"
#include "B.h"
#include "C.h"
each .h header are protected with include guard such as
#ifndef A_HEADER
#define A_HEADER
...
#endif
The issues is, I would like to be able to include "framework.h" inside all the sub .h such as, but it cause lots of compiler error:
#ifndef A_HEADER
#define A_HEADER
#include "framework.h"
...
#endif
If instead I use the real header file for each sub header, and the framework.h for what ever use my framework it works fine..
I would just like to include the main header inside all my sub .h so I dont need to include all the dependency everytime.
Thanks :)
| Basically what your doing is #include "A.h" in framework.h and #include "framework.h" in A.h. This causes cyclic dependency of the header files and you will get errors such as undefined class A. To solve this, use forward declarations in header file and #include only in corresponding cpp file. If that is not possible then I don't see any other option other than including individual header files.
|
2,866,878 | 2,867,583 | C++ hash table w/o using STL | I need to create a hash table that has a key as a string, and value as an int. I cannot use STL containers on my target. Is there a suitable hash table class for this purpose?
| Here's a quick a dirty C hash I just wrote. Compiles, but untested locally. Still, the idea is there for you to run with it as needed. The performance of this is completely dependant upon the keyToHash function. My version will not be high performance, but again demonstrates how to do it.
static const int kMaxKeyLength = 31;
static const int kMaxKeyStringLength = kMaxKeyLength + 1;
struct HashEntry
{
int value;
char key[kMaxKeyLength];
};
static const char kEmptyHash[2] = "";
static const int kHashPowerofTwo = 10;
static const int kHashSize = 1 << kHashPowerofTwo;
static const int kHashMask = kHashSize - 1;
static const int kSmallPrimeNumber = 7;
static HashEntry hashTable[kHashSize];
int keyToHash(const char key[])
{
assert(strlen(key) < kMaxKeyLength);
int hashValue = 0;
for(int i=0; < strlen(key); i++)
{
hashValue += key[i];
}
return hashValue;
}
bool hashAdd(const char key[], const int value)
{
int hashValue = keyToHash(key);
int hashFullSentinal = 0;
while(strcmp(hashTable[hashValue & kHashMask].key, kEmptyHash))
{
hashValue += kSmallPrimeNumber;
if(hashFullSentinal++ >= (kHashSize - 1))
{
return false;
}
}
strcpy(hashTable[hashValue & kHashMask].key, key);
hashTable[hashValue & kHashMask].value = value;
return true;
}
bool hashFind(const char key[], int *value)
{
int hashValue = keyToHash(key);
while(strcmp(hashTable[hashValue & kHashMask].key, kEmptyHash))
{
if(!strcmp(hashTable[hashValue & kHashMask].key, key))
{
*value = hashTable[hashValue & kHashMask].value;
return true;
}
}
return false;
}
bool hashRemove(const char key[])
{
int hashValue = keyToHash(key);
while(strcmp(hashTable[hashValue & kHashMask].key, kEmptyHash))
{
if(!strcmp(hashTable[hashValue & kHashMask].key, key))
{
hashTable[hashValue & kHashMask].value = 0;
hashTable[hashValue & kHashMask].key[0] = 0;
return true;
}
}
return false;
}
|
2,866,897 | 2,866,929 | what happens when you copy vector<boost::share_ptr> to another vector | Do we get multiple copies of the pointers yet the data members are still being shared?
boost::shared_ptr<string> a1(new string("Hello"));
vector<boost::shared_ptr<string> > a;
a.push_back(a1);
vector<boost::shared_ptr<string> > b;
b = a;
cout<<a[0]->c_str()<<b[0]->c_str()<<endl;
a1->append(" World");
cout<<a[0]->c_str()<<b[0]->c_str()<<endl;
Output:
HelloHello
Hello WorldHello World
| Yes. But don't take my word for it, try it and see.
|
2,867,340 | 2,867,483 | How to create a string array in MATLAB? | I would like to pass a vector of strings from C++ to MATLAB. I have tried using the functions available such as mxCreateCharMatrixFromStrings, but it doesn't give me the correct behavior.
So, I have something like this:
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
vector<string> stringVector;
stringVector.push_back("string 1");
stringVector.push_back("string 2");
//etc...
The problem is how do I get this vector to the matlab environment?
plhs[0] = ???
My goal is to be able to run:
>> [strings] = MyFunc(...)
>> strings(1) = 'string 1'
| Storing a vector of strings as a char matrix requires that all of your strings are the same length and that they're stored contiguously in memory.
The best way to store an array of strings in MATLAB is with a cell array, try using mxCreateCellArray, mxSetCell, and mxGetCell. Under the hood, cell arrays are basically an array of pointers to other objects, char arrays, matrices, other cell arrays, etc..
|
2,867,451 | 2,868,355 | Is is possible to make a shaped, alpha-blended dialog? | I'm making a non-rectangular dialog, modelled over an image from Photoshop (the image is the background of the dialog, and the user will see trough the transparent part of the image). I'ts like a dashboard-style window for a media-app with a few custom-drawn controls. Most of the background-image is either opaque or 100% transparent - but in between there is a thin area of partially transparent pixels, ment to blend the image smootly into the background. This works great for web-graphics, but I have not found a way to make this work for Windows windows. I'm using the Windows Template Library (WTL), msvc 2008 - and the app must run on Windows XP as well as Vista and Windows 7.
Currently, I'm simply using the opaque part of the background-image to create a GDI clipping-region, but this gives pretty rough edges.
Does anyone know about any API functions to accomplish this (part of WTL, or reachable from WTL)?
| Perhaps you could use layered windows? I haven't tested these with WTL but you should be able to get the effect you want. To the best of my knowledge I don't think you can add controls to a layered window so you'll need to attach it to another (non-layered) window to use controls.
|
2,867,511 | 2,867,535 | Const Functions and Interfaces in C++ | I'll use the following (trivial) interface as an example:
struct IObject
{
virtual ~IObject() {}
virtual std::string GetName() const = 0;
virtual void ChangeState() = 0;
};
Logic dictates that GetName should be a const member function while ChangeState shouldn't.
All code that I've seen so far doesn't follow this logic, though. That is, GetName in the example above wouldn't be marked as a const member function.
Is this laziness/carelessness or is there a legitimate reason for this? What are the major cons of me forcing my clients to implement const member functions when they are logically called for?
EDIT: Thanks for your responses everyone. I think it's pretty much unanimous: laziness/ignorance is the reason for what I'm seeing.
| I think it's laziness/carelessness. GetName() should have no effect on the object's state, and the contract of IObject should state that fact explicitly.
If the inheriting class was somehow forced to make GetName() have (hidden!) side effects, they could always declare the corresponding fields as mutable.
|
2,867,666 | 2,867,693 | C++: Filling vector from the pipe | I would like to fill my vector<float> from command line:
more my.txt | myexe.x > result.txt
What is the best way to open the pipe in C++?
Thanks
Arman.
| Your shell will connect the standard output of more to the standard input of myexe.x. So you can just read from std::cin, and need not worry whether the input comes from the keyboard or from some other program.
For example:
vector<float> myVec;
copy(istream_iterator<float>(cin), istream_iterator<float>(),
back_inserter(myVec));
|
2,867,755 | 2,868,732 | What does IUrlHistoryStg::BindToObject Method do? | I'm looking for a way to access the address bar search so that i can append some personnal url at the end of the current list, and i found 'IUrlHistoryStg::BindToObject' but there is no documention linked to it. Anyone knows what this method does ?
On msdn: http://msdn.microsoft.com/en-us/library/aa767718%28VS.85%29.aspx
| It's not implemented, so it doesn't do anything. It was a bad idea that didn't get removed in time to not have it be in the SDK.
Use IShellFolder::BindToObject() instead.
|
2,867,758 | 2,867,832 | How to generate a LONG guid? | I would like to generate a long UUID - something like the session key used by gmail. It should be at least 256 chars and no more than 512. It can contain all alpha-numeric chars and a few special chars (the ones below the function keys on the keyboard). Has this been done already or is there a sample out there?
C++ or C#
Update: A GUID is not enough. We already have been seeing collisions and need to remedy this. 512 is the max as of now because it will prevent us from changing stuff that was already shipped.
Update 2: For the guys who are insisting about how unique the GUID is, if someone wants to guess your next session ID, they don't have to compute the combinations for the next 1 trillion years. All they have to do is use constrain the time factor and they will be done in hours.
| As per your update2 you are correct on Guids are predicable even the msdn references that. here is a method that uses a crptographicly strong random number generator to create the ID.
static long counter; //store and load the counter from persistent storage every time the program loads or closes.
public static string CreateRandomString(int length)
{
long count = System.Threading.Interlocked.Increment(ref counter);
int PasswordLength = length;
String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789";
Byte[] randomBytes = new Byte[PasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
{
while(randomBytes[i] > byte.MaxValue - (byte.MaxValue % allowedCharCount))
{
byte[] tmp = new byte[1];
rng.GetBytes(tmp);
randomBytes[i] = tmp[0];
}
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
}
byte[] buf = new byte[8];
buf[0] = (byte) count;
buf[1] = (byte) (count >> 8);
buf[2] = (byte) (count >> 16);
buf[3] = (byte) (count >> 24);
buf[4] = (byte) (count >> 32);
buf[5] = (byte) (count >> 40);
buf[6] = (byte) (count >> 48);
buf[7] = (byte) (count >> 56);
return Convert.ToBase64String(buf) + new string(chars);
}
EDIT I know there is some biasing because allowedCharCount is not evenly divisible by 255, you can get rid of the bias throwing away and getting a new random number if it lands in the no-mans-land of the remainder.
EDIT2 - This is not guaranteed to be unique, you could hold a static 64 bit(or higher if necessary) monotonic counter encode it to base46 and have that be the first 4-5 characters of the id.
UPDATE - Now guaranteed to be unique
UPDATE 2: Algorithm is now slower but removed biasing.
EDIT: I just ran a test, I wanted to let you know that ToBase64String can return non alphnumeric charaters (like 1 encodes to "AQAAAAAAAAA=") just so you are aware.
New Version:
Taking from Matt Dotson's answer on this page, if you are no so worried about the keyspace you can do it this way and it will run a LOT faster.
public static string CreateRandomString(int length)
{
length -= 12; //12 digits are the counter
if (length <= 0)
throw new ArgumentOutOfRangeException("length");
long count = System.Threading.Interlocked.Increment(ref counter);
Byte[] randomBytes = new Byte[length * 3 / 4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
byte[] buf = new byte[8];
buf[0] = (byte)count;
buf[1] = (byte)(count >> 8);
buf[2] = (byte)(count >> 16);
buf[3] = (byte)(count >> 24);
buf[4] = (byte)(count >> 32);
buf[5] = (byte)(count >> 40);
buf[6] = (byte)(count >> 48);
buf[7] = (byte)(count >> 56);
return Convert.ToBase64String(buf) + Convert.ToBase64String(randomBytes);
}
|
2,867,821 | 2,910,806 | C++ boost::lambda::ret equivalent in phoenix | Boost lambda allows to overwrite deduced return type using ret<T> template.
I have tried searching for equivalent in phoenix but could not find one.
Is there an equivalent in phoenix? I know how to make my own Replacement but I would rather not. thank you
| Rewrite: I missed the point on my first answer (it was late), let me try again.
Let me give some exposition for people like me who might miss your point the first time. In boost::lambda, when using user defined types in operator expressions, one has to use the ret<> function to override return type deduction. This is because the lambda return type deduction system only supports native (and stl? I don't remember) types directly. A short example:
using namespace boost::lambda;
struct add_t{
add_t(int i) : i(i) {};
add_t operator+(const add_t& other) const{
return add_t(i + other.i);
}
int i;
};
(_1 + _2)(add_t(38), add_t(4)); // RETURN TYPE DEDUCTION FAILS
ret<add_t>(_1 + _2)(add_t(38), add_t(4)); // OK
In phoenix though, no hints are are needed (note that literals and non-const temporaries cannot appear in a phoenix argument list):
using namespace boost::phoenix;
add_t i(38), j(4);
(_1 + _2)(i, j); // JUST FINE
The return type deduction system is completely different and much more natural in phoenix; it will properly deduce the return type of operators that use conventional semantics. Specifically, the return type should match the type of one of the operands, be a reference, pointer, or const pointer to one of the argument types, or be an stl container/container iterator of one of those types. There is a nice write up of phoenix return type deduction in type_deduction.hpp header for more details.
So now I'm reading your question as, how can non-conventional operator semantics be handled in phoenix?
Consider the following strange pair of types as an example
struct add_ret_t{
add_ret_t(int i) : i(i) {};
int i;
};
struct add_t{
add_t(int i) : i(i) {};
add_ret_t operator+(const add_t& other) const{
return add_ret_t(i + other.i);
}
int i;
};
For lambda, this is no problem, just use the ret function:
using namespace boost::lambda;
ret<add_ret_t>(_1 + _2)(add_t(38), add_t(4)); // OK
But phoenix can't deal with this operator (can you blame it?) because the return type is not related to the arguments, and there is no way to directly indicate the return type in phoenix. If there is a good reason to use an operator like this, a case could be added to the type deduction system, but I can't see a way to do this without hacking type_deduction.hpp or branching a good portion of phoenix.
Alternatively, I figured out a little hack to override the return types for specific operators. The result_of_operation template structures in boost/spirit/home/phoenix/operator/arithmetic.hpp (lines 39-56 list the struct types, boost 1.43) execute the type deduction when they are instantiated and store the result. So all that is needed is to provide some template specializations for the problem operations, which only need contain one typedef specifying the return type. Example (codepad for full src):
using namespace boost::phoenix;
namespace boost{ namespace phoenix{
//override add_t addition to give add_ret_t
template <> struct result_of_plus<add_t&, add_t&> { typedef add_ret_t type; };
//override int addition to give char
template <> struct result_of_plus<int&, int&> { typedef char type; };
}}
int main()
{
add_t i = 1, j = 7;
std::cout << ((_1 + _2)(i, j)).i << std::endl;
int k = 51, l = 37;
std::cout << ((_1 + _2)(k, l)) << std::endl;
return 0;
}
This certainly isn't a ret replacement, but in some senses its better since its global. If there are a lot of operators to overload, the full set of operations could be macroed.
|
2,868,121 | 2,868,141 | What is the problem with this code? | #include<stdio.h>
class A { public: int a;};
class B: public A {
public:
static int b;
B(){
b++;
printf("B:%d\n",b);
}
};
int main() {
A* a1 = new B[100];
A* a2 = new B();
return 0;
}
Error:
In function `main':
undefined reference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'
| Static variables need to be allocated outside the class. Add this line outside the class B:
int B::b;
Think of static variables as being declared with the extern keyword. They still need to be allocated somewhere. This means the allocation should never be in the header file!
|
2,868,301 | 2,868,319 | Why does C++ behave this way? | #include<stdio.h>
class A { public: int a;};
class B: public A {
int c;
int d;
};
int main() {
A* pA = new B[10];
B* pB = new B[10];
printf("\n%d", pA->a);
pA++;
printf("\n%d", pA->a); // prints junk value
printf("\n\n%d", pB->a);
pB++;
printf("\n%d", pB->a);
return 0;
}
The second printf prints a junk value.
It should figure that it is pointing to an object of type B and increment by the sizof(B).
Why does that not happen?
| It can only know that at runtime. Imagine it slightly changed
A* a;
if(runtimevalue)
a = new A[10];
else
a = new B[10];
But that's not going to happen. C++ puts emphasize in speed, but this would basically make it into a language that ensures safety of operations. There is Java, C# and others that already solve this.
Kernel and device driver developers don't want a clever language runtime. They just want to have things run fast.
Have a look at Common undefined behavior in C++ question for all the things that will need to get "fixed" along. It won't be C++ anymore!
|
2,868,351 | 2,868,887 | Windows Threading: beginthread or QueueUserWorkItem (C++) | I am wondering whether to use beginthread or QueueUserWorkItem for threaded methods in C++. What are the differences between the two APIs and in what context are they better suited?
Thanks,
BTW, I have read this question Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
| QUWI uses a thread from the thread pool to execute the callback function. Such threads are very light weight but not suitable for all types of threaded tasks. Basic requirements are that they need to be relatively short-lived, don't block very often and are not time critical.
It is all rather well explained in the SDK topic.
|
2,868,373 | 2,868,572 | C++ Beginner - Simple block of code crashing, reason unknown | Here's a block of code I'm having trouble with.
string Game::tradeRandomPieces(Player & player)
{
string hand = player.getHand();
string piecesRemoved;
size_t index;
//Program crashes while calculating numberOfPiecesToTrade...
size_t numberOfPiecesToTrade = rand() % hand.size() + 1
for (; numberOfPiecesToTrade != 0; --numberOfPiecesToTrade)
{
index = rand() % hand.size();
piecesRemoved += hand[index];
hand.erase(index,1);
}
player.removePiecesFromHand(piecesRemoved);
player.fillHand(_deck);
return piecesRemoved;
}
I believe the code is pretty self explanatory.
fillhand and removepiecesfromhand are working fine, so that's not it.
I really can't get what's wrong with this :(
Thanks for your time
EDIT
OK, I found out where the program crashes. Added a comment to the above source code.
| stick a breakpoint into your for loop to give you a better idea of what's going on. I would bet that the for loop is going infinite and causing the program to hang.
On hitting the breakpoint, check your iterator variables and see if you can see anything out of the ordinary
|
2,868,439 | 2,868,506 | Is there a way to limit an integer value to a certain range without branching? | Just out of curiosity. If I have something like:
if(x < 0)
x = 0;
if(x > some_maximum)
x = some_maximum;
return x;
Is there a way to not branch? This is c++.
Addendum: I mean no branch instructions in the assembly. It's a MIPS architecture.
| There are bit-tricks to find the minimum or maximum of two numbers, so you could use those to find min(max(x, 0), some_maximum). From here:
y ^ ((x ^ y) & -(x < y)); // min(x, y)
x ^ ((x ^ y) & -(x < y)); // max(x, y)
As the source states though, it's probably faster to do it the normal way, despite the branch
|
2,868,485 | 2,868,527 | Cast vector<T> to vector<const T> | I have a member variable of type vector<T> (where is T is a custom class, but it could be int as well.)
I have a function from which I want to return a pointer to this vector, but I don't want the caller to be able to change the vector or it's items. So I want the return type to be const vector<const T>*
None of the casting methods I tried worked. The compiler keeps complaining that T is not compatible with const T.
Here's some code that demonstrates the gist of what I'm trying to do;
vector<int> a;
const vector<const int>* b = (const vector<const int>* ) (&a);
This code doesn't compile for me.
Thanks in advance!
| If you have a const vector<int> you cannot modify the container, nor can you modify any of the elements in the container. You don't need a const vector<const int> to achieve those semantics.
|
2,868,493 | 2,869,398 | How to return array of C++ objects from a PHP extension | I need to have my PHP extension return an array of objects, but I can't seem to figure out how to do this.
I have a Graph object written in C++. Graph.getNodes() returns a std::map<int, Node*>. Here's the code I have currently:
struct node_object {
zend_object std;
Node *node;
};
zend_class_entry *node_ce;
then
PHP_METHOD(Graph, getNodes)
{
Graph *graph;
GET_GRAPH(graph, obj) // a macro I wrote to populate graph
node_object* n;
zval* node_zval;
if (obj == NULL) {
RETURN_NULL();
}
if (object_init_ex(node_zval, node_ce) != SUCCESS) {
RETURN_NULL();
}
std::map nodes = graph->getNodes();
array_init(return_value);
for (std::map::iterator i = nodes.begin(); i != nodes.end(); ++i) {
php_printf("X");
n = (node_object*) zend_object_store_get_object(node_zval TSRMLS_CC);
n->node = i->second;
add_index_zval(return_value, i->first, node_zval);
}
php_printf("]");
}
When i run php -r '$g = new Graph(); $g->getNodes();' I get the output
XX]Segmentation fault
meaning the getNodes() function loops successfully through my 2-node list, returns, then segfaults. What am I doing wrong?
| I simply needed to MAKE_STD_ZVAL(node_zval). A secondary issue with this code was that I was reusing this zval pointer, thus overwriting every previous zval and ending up with an array full of the same object. To remedy this, I initialize node_zval for each loop. Here's the final code:
PHP_METHOD(Graph, getNodes)
{
Graph *graph;
GET_GRAPH(graph, obj) // a macro I wrote to populate graph
node_object* n;
zval* node_zval;
if (obj == NULL) {
RETURN_NULL();
}
std::map nodes = graph->getNodes();
array_init(return_value);
for (std::map::iterator i = nodes.begin(); i != nodes.end(); ++i) {
MAKE_STD_ZVAL(node_zval);
if (object_init_ex(node_zval, node_ce) != SUCCESS) {
RETURN_NULL();
}
n = (node_object*) zend_object_store_get_object(node_zval TSRMLS_CC);
n->node = i->second;
add_index_zval(return_value, i->first, node_zval);
}
}
|
2,868,662 | 2,879,690 | SWT-like GUI toolkit for C or C++ | Do you know any cross-platform GUI toolkit like swt for C (using default widgets in each operating system = right pics on eclipse.org/swt) ? There is an implementation of swt for D language called DWT but I need it for C or C++. Thanks.
|
Qt (community)
wxWidgets
FLTK
GTK+
FOX
Notus
VCF - EDIT2 seems to be inactive for a few years
You can read some details in that wiki.
First 4 are pretty popular, the rest I dont know.
EDIT:
8. There is C++ port but it seem Windows only for now
9. SWT/Fox - C++ port on top of FOX toolkit - seems to be dead for more then 3 years
10. Also you can try .NET + Mono. But not for commercial project, I think
Qt, FLTK and GTK+ use their own widgets system, i.e. they replace native windows, buttons, etc. Whereas wxWidgets provides a layer on top of native system. Hence:
with wxWidgets you get 100% native look&feel on every platform without any effort.
CON - you get native bugs too :). Different behaviour could be undesirable
At least Qt can emulate native look&feel (some people say it is not perfect on MacOS X). Also KDE is written in Qt, so for KDE desktops Qt is native
EDIT2:
Just found this really extensive list of widget toolkits on wikipedia
|
2,868,673 | 2,868,992 | How to support comparisons for QVariant objects containing a custom type? | According to the Qt documentation, QVariant::operator== does not work as one might expect if the variant contains a custom type:
bool QVariant::operator== ( const QVariant & v ) const
Compares this QVariant with v and
returns true if they are equal;
otherwise returns false.
In the case of custom types, their
equalness operators are not called.
Instead the values' addresses are
compared.
How are you supposed to get this to behave meaningfully for your custom types? In my case, I'm storing an enumerated value in a QVariant, e.g.
In a header:
enum MyEnum { Foo, Bar };
Q_DECLARE_METATYPE(MyEnum);
Somewhere in a function:
QVariant var1 = QVariant::fromValue<MyEnum>(Foo);
QVariant var2 = QVariant::fromValue<MyEnum>(Foo);
assert(var1 == var2); // Fails!
What do I need to do differently in order for this assertion to be true?
I understand why it's not working -- each variant is storing a separate copy of the enumerated value, so they have different addresses. I want to know how I can change my approach to storing these values in variants so that either this is not an issue, or so that they do both reference the same underlying variable.
It don't think it's possible for me to get around needing equality comparisons to work. The context is that I am using this enumeration as the UserData in items in a QComboBox and I want to be able to use QComboBox::findData to locate the item index corresponding to a particular enumerated value.
| The obvious answer is to cast the data out of with var1.value<MyEnum>() == var2.value<MyEnum>() to compare them, but that requires you to know the type when comparing. It seems like in your case this might be possible.
If you are just using enums, you could also convert it to an int for storage in the QVariant.
Edit: For clarification about searching a QComboBox, it uses the model of the combo box to find the data. Specifically, it uses the match() function of the QAbstractItemModel to check for equality. Luckily, this function is virtual so you can override it in a subclass.
|
2,868,680 | 2,868,729 | What is a cross-platform way to get the current directory? | I need a cross-platform way to get the current working directory (yes, getcwd does what I want). I thought this might do the trick:
#ifdef _WIN32
#include <direct.h>
#define getcwd _getcwd // stupid MSFT "deprecation" warning
#elif
#include <unistd.h>
#endif
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s_cwd(getcwd(NULL,0));
cout << "CWD is: " << s_cwd << endl;
}
I got this reading:
_getcwd at MSDN
getcwd at Kernel.org
getcwd at Apple.com
There should be no memory leaks, and it should work on a Mac as well, correct?
UPDATE: I fear something is still wrong here (I'm trying to avoid creating a char array with a determined length, as there's no proper way to get a decent length for getcwd):
char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_cwd); // or delete a_cwd?
| If it is no problem for you to include, use boost filesystem for convenient cross-platform filesystem operations.
boost::filesystem::path full_path( boost::filesystem::current_path() );
Here is an example.
EDIT: as pointed out by Roi Danton in the comments, filesystem became part of the ISO C++ in C++17, so boost is not needed anymore:
std::filesystem::current_path();
|
2,868,955 | 2,868,971 | shielding #include within namespace { } block? | Edit: I know that method 1 is essentially invalid and will probably use method 2, but I'm looking for the best hack or a better solution to mitigate rampant, mutable namespace proliferation.
I have multiple class or method definitions in one namespace that have different dependencies, and would like to use the fewest namespace blocks or explicit scopings possible but while grouping #include directives with the definitions that require them as best as possible. I've never seen any indication that any preprocessor could be told to exclude namespace {} scoping from #include contents, but I'm here to ask if something similar to this is possible: (see bottom for explanation of why I want something dead simple)
// NOTE: apple.h, etc., contents are *NOT* intended to be in namespace Foo!
// would prefer something most this:
#pragma magic_namespace_backout(1) // FIXME: use actually existing directive
namespace Foo {
#include "apple.h"
B *A::blah(B const *x) { /* ... */ }
#include "banana.h"
int B::whatever(C const &var) { /* ... */ }
#include "blueberry.h"
void B::something() { /* ... */ }
} // namespace Foo
...
// over this:
#include "apple.h"
#include "banana.h"
#include "blueberry.h"
namespace Foo {
B *A::blah(B const *x) { /* ... */ }
int B::whatever(C const &var) { /* ... */ }
void B::something() { /* ... */ }
} // namespace Foo
...
// or over this:
#include "apple.h"
namespace Foo {
B *A::blah(B const *x) { /* ... */ }
} // namespace Foo
#include "banana.h"
namespace Foo {
int B::whatever(C const &var) { /* ... */ }
} // namespace Foo
#include "blueberry.h"
namespace Foo {
void B::something() { /* ... */ }
} // namespace Foo
My real problem is that I have projects where a module may need to be branched but have coexisting components from the branches in the same program. I have classes like FooA, etc., that I've called Foo::A in the hopes being able to branch less painfully as Foo::v1_2::A, where some program may need both a Foo::A and a Foo::v1_2::A. I'd like "Foo" or "Foo::v1_2" to show up only really once per file, as a single namespace block, if possible. Moreover, I tend to prefer to locate blocks of #include directives immediately above the first definition in the file that requires them. What's my best choice, or alternatively, what should I be doing instead of hijacking the namespaces?
| Just think of #including as copying and pasting the contents of the included file to the position of the #include directive.
That means, yes, everything in the included file will be inside the namespace.
|
2,868,956 | 2,869,003 | lambda+for_each+delete on STL containers | I'm trying to get a simple delete every pointer in my vector/list/... function written with an ultra cool lambda function.
template <typename T>
void delete_clear(T const& cont)
{
for_each(T.begin(), T.end(), [](???){ ???->delete() } );
}
I have no clue what to fill in for the ???'s. Any help is greatly appreciated!
UPDATE: This is what it should look like:
template <typename Container>
void delete_clear(Container &c)
{
for_each(c.begin(), c.end(), [](typename Container::value_type x){ delete x; } );
c.clear();
}
| Two issues here: the lambda syntax itself, and how to get the value type of a container:
To call the mydelete() function on each pointer (assuming you've defined a mydelete() member function):
for_each(c.begin(), c.end(), [](typename T::value_type x){ x->mydelete(); } );
To delete them using the delete operator:
for_each(c.begin(), c.end(), [](typename T::value_type x){ delete x; } );
Also, lambda isn't necessarily the coolest new feature in C++11 for a given problem:
for(auto x : c) { delete x; }
I'd note that it's a bit dodgy to take a const reference to a container, and delete everything in it, although the language doesn't stop you because of what pointers are. Are you sure that's a "constant" operation, though, within the meaning and use of your container?
If you're writing this code, maybe you'd benefit from Boost pointer containers, or containers of shared_ptr.
|
2,869,183 | 2,869,584 | Segmentation fault in std function std::_Rb_tree_rebalance_for_erase () | (Note to any future readers: The error, unsurprisingly, is in my code and not std::_Rb_tree_rebalance_for_erase () )
I'm somewhat new to programming and am unsure how to deal with a segmentation fault that appears to be coming from a std function. I hope I'm doing something stupid (i.e., misusing a container), because I have no idea how to fix it.
The precise error is
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x000000000000000c
0x00007fff8062b144 in std::_Rb_tree_rebalance_for_erase ()
(gdb) backtrace
#0 0x00007fff8062b144 in std::_Rb_tree_rebalance_for_erase ()
#1 0x000000010000e593 in Simulation::runEpidSim (this=0x7fff5fbfcb20) at stl_tree.h:1263
#2 0x0000000100016078 in main () at main.cpp:43
The function that exits successfully just before the segmentation fault updates the contents of two containers. One is a boost::unordered_multimap called carriage; it contains one or more struct Infection objects. The other container is of type std::multiset< Event, std::less< Event > > EventPQ called ce.
void Host::recover( int s, double recoverTime, EventPQ & ce ) {
// Clearing all serotypes in carriage
// and their associated recovery events in ce
// and then updating susceptibility to each serotype
double oldRecTime;
int z;
for ( InfectionMap::iterator itr = carriage.begin(); itr != carriage.end(); itr++ ) {
z = itr->first;
oldRecTime = (itr->second).recT;
EventPQ::iterator epqItr = ce.find( Event(oldRecTime) );
assert( epqItr != ce.end() );
ce.erase( epqItr );
immune[ z ]++;
}
carriage.clear();
calcSusc(); // a function that edits an array
cout << "Done with sync_recovery event." << endl;
}
The last cout << line appears immediately before the seg fault.
My idea so far is that the rebalancing is being attempted on ce immediately after this function, but I am unsure why the rebalancing would be failing.
Update
I've confirmed the seg fault goes away (though the program then immediately crashes for other reasons) when I remove ce.erase( epqItr );. I am able to remove events successfully in another place in the code; the code I use there to erase items in ce is identical to what's here.
Backtracing without optimization (thanks, bdk) reveals much more information:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x000000000000000c
0x00007fff8062b144 in std::_Rb_tree_rebalance_for_erase ()
(gdb) backtrace
#0 0x00007fff8062b144 in std::_Rb_tree_rebalance_for_erase ()
#1 0x00000001000053d2 in std::_Rb_tree, std::less, > std::allocator >::erase (this=0x7fff5fbfdfe8, __position={_M_node = 0x10107cb50}) at > stl_tree.h:1263
#2 0x0000000100005417 in std::multiset, std::allocator >::erase (this=0x7fff5fbfdfe8, __position={_M_node = 0x10107cb50}) at stl_multiset.h:346
#3 0x000000010000ba71 in Simulation::runEpidSim (this=0x7fff5fbfcb40) at Simulation.cpp:426
#4 0x000000010001fb31 in main () at main.cpp:43
Unless Xcode is reading line numbers wrong, the only stl_tree.h in my hard drive is blank on line 1263.
A few people asked to see the function that calls recover. It's a bit complicated:
struct updateRecovery{
updateRecovery( int s, double t, EventPQ & ce ) : s_(s), t_(t), ce_(ce) {}
void operator() (boost::shared_ptr<Host> ptr ) {
ptr->recover( s_, t_, ce_ );
}
private:
int s_;
double t_;
EventPQ & ce_;
};
// allHosts is a boost::multiindex container of boost::shared_ptr< Host >
// currentEvents is the EventPQ container
// it is an iterator to a specific member of allHosts
allHosts.modify( it, updateRecovery( s, t, currentEvents ) );
cout << "done with recovery" << endl;
The last cout prints. The code worked before without this particular version of the recovery function.
Noah Roberts correctly pointed out that the problem is at Simulation.cpp, line 426. Jump below for embarrassing solution.
| Possibly you're holding onto an iterator into ce across the call to recover. If recover happens to remove that item the iterator will be invalidated and any future use (say an attempt to erase it) could result in a seg fault.
It would help if we could see more context of how ce is used before and after the call to recover.
|
2,869,515 | 2,871,936 | What should be done in place of ddeexec for MDI apps? | We have been using ddeexec registry entries to handle opening a design from Explorer.
MSDN (about 2/3 way into article) indicates that ddeexec is deprecated, and applications should use IDropTarget instead.
What is unclear to me is how that this actually is supposed to work..
e.g. If I have Foo.exe, which is intended to handle .foo files, what does the registry look like?
HKCR\.foo
(default) = Foo.foo.1
HKCR\Foo.foo.1
shell
open
command
(default) = ?????
If the command is set to the obvious:
"C:\Program Files\Foo Corp\Foo.exe" "%1"
then Foo.exe is launched each time the user double clicks on, or chooses open from the context menu for a .foo file.
However, that means a separate instance of Foo.exe is launched for every file that the user attempts to launch. YUCK.
I can certainly write custom code to somehow pass on the filename from the 2nd instance of Foo.exe back to the first instance of Foo.exe and then exit... but then I'm writing a fair bit of custom code.
DDE used to handle this gracefully (enough) by asking the already running first instance of Foo.exe to open the specified file. This made it easy to have an MDI app skillfully handle opening multiple documents, where each one was opened within the one instance of Foo.exe.
If DDE is deprecated, then what is the preferred mechanism? Our app makes much more sense as an MDI app - we certainly don't want several instances of Foo.exe running (that would only annoy our users). I certainly don't want to have to write a new Foo-Shim.exe which looks for the real instance of Foo.exe, and uses some custom mechanism to pass the filename being opened to it. (I can't just use Foo.exe for this purpose, because Foo.exe is big, and slow to load, and requires an activation security code which is counted per instance, and so may refuse to start up if you're at your maximum concurrent user limit).
I don't see anything in IDropTarget which looks like it has much of anything to do with this (common) scenario.
Does anyone know what MS intended here?
| When you use IDropTarget, it simulates a drag&drop (XP and later, you must use DDE or whatever on older systems)
As luck would have it, Raymond Chen recently did a blog post about IDropTarget with sample code.
|
2,869,552 | 2,869,688 | Simple average calculation | I'm trying to write program calculating average of given numbers stored in an array. Amount of numbers should be not more than 100, and user should input them until a !int variable is given :
#include <iostream>
#include <conio.h>
using namespace std;
double average(int tab[], int i){
int sum=0;
for(int j=0; j<i; ++j){
sum+=tab[j];
}
return (double)sum/i;
}
int main()
{
int tab[100];
int n=0;
int number=0;
do {
if(n < 100){
cout << "Give " << n+1 << " number : ";
cin >> number;
tab[n]=number;
number=0;
++n;
}
else{
break;
}
} while( !isdigit(number) );
cout << average(tab, n) << endl;
getch();
return 0;
}
Why after giving char, it prints me 'Give n number:' for all empty cells of my array ? It should end and use only given numbers.
| isdigit tests whether the character is a digit. The test is only reached following assigning 0 to number, and 0 is a control code, not a digit, so isdigit(0) is always false, and so your while condition is always true.
...
number=0;
...
} while( !isdigit(number) );
Instead, test the input stream to determine whether it successfully read a value.
int main()
{
const size_t COUNT = 100;
int tab[COUNT];
size_t n;
cin.tie(&cout); // ensures cout flushed before cin read
// (not required if your runtime complies with that part of the standard)
for (n = 0; n < COUNT; ++n ) {
cout << "Give " << n+1 << " number : ";
cin >> tab[n];
if (!cin)
break;
}
if (n > 0) // average is undefined if n == 0
cout << average(tab, n) << endl;
return 0;
}
|
2,869,594 | 2,869,667 | How return a std::string from C's "getcwd" function | Sorry to keep hammering on this, but I'm trying to learn :). Is this any good? And yes, I care about memory leaks. I can't find a decent way of preallocating the char*, because there simply seems to be no cross-platform way.
const string getcwd()
{
char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_cwd);
return s_cwd;
}
UPDATE2: without Boost or Qt, the most common stuff can get long-winded (see accepted answer)
| If you want to remain standard, getcwd isn't required to do anything if you pass to it a NULL; you should instead allocate on the stack a buffer that is "large enough" for most occasions (say, 255 characters), but be prepared for the occasion in which getcwd may fail with errno==ERANGE; in that case you should allocate dinamically a bigger buffer, and increase its size if necessary.
Something like this could work (notice: not tested, just written by scratch, can be surely improved):
string getcwd()
{
const size_t chunkSize=255;
const int maxChunks=10240; // 2550 KiBs of current path are more than enough
char stackBuffer[chunkSize]; // Stack buffer for the "normal" case
if(getcwd(stackBuffer,sizeof(stackBuffer))!=NULL)
return stackBuffer;
if(errno!=ERANGE)
{
// It's not ERANGE, so we don't know how to handle it
throw std::runtime_error("Cannot determine the current path.");
// Of course you may choose a different error reporting method
}
// Ok, the stack buffer isn't long enough; fallback to heap allocation
for(int chunks=2; chunks<maxChunks ; chunks++)
{
// With boost use scoped_ptr; in C++0x, use unique_ptr
// If you want to be less C++ but more efficient you may want to use realloc
std::auto_ptr<char> cwd(new char[chunkSize*chunks]);
if(getcwd(cwd.get(),chunkSize*chunks)!=NULL)
return cwd.get();
if(errno!=ERANGE)
{
// It's not ERANGE, so we don't know how to handle it
throw std::runtime_error("Cannot determine the current path.");
// Of course you may choose a different error reporting method
}
}
throw std::runtime_error("Cannot determine the current path; the path is apparently unreasonably long");
}
By the way, in your code there's a very wrong thing: you are trying to dellocate a_cwd (which presumably, in the nonstandard extension, is allocated with malloc or with some other memory allocation function, since getcwd is thought for C) with delete: you absolutely shouldn't do that, keep in mind that each allocation method has its deallocation counterpart, and they must not be mismatched.
|
2,869,785 | 2,870,146 | Point to point linear gradient? | I want to make an application that can generate point to point gradient (like Photoshop does). I'm familiar with how to generate an up to down gradient but not point to point. How is this conceptually done.
Thanks
| I can't say if this is exactly how Photoshop does it, or that it's the most optimal way of doing it, but this should be the basic principle.
Think of the two points as defining a vector. You can find a normal vector for this, which will be perpendicular to the original vector (since that's the definition of a normal vector).
For each discrete point (pixel) on the line, calculate the gradient color as you would for an up-down (or left-right) gradient of the same length as your vector. Then draw a line of the selected color, such that it passes through the currently chosen point and is parallel with the normal vector.
It's actually very similar to the approach you'd use for an up-down gradient, except it's rotated.
|
2,870,005 | 2,877,608 | Boost Binary Endian parser not working? | I am studying how to use boost spirit Qi binary endian parser. I write a small test parser program according to here and basics examples, but it doesn't work proper. It gave me the msg:"Error:no match".
Here is my code.
#include "boost/spirit/include/qi.hpp"
#include "boost/spirit/include/phoenix_core.hpp"
#include "boost/spirit/include/phoenix_operator.hpp"
#include "boost/spirit/include/qi_binary.hpp" // parsing binary data in various endianness
template "<"typename P, typename T>
void binary_parser( char const* input, P const& endian_word_type,
T& voxel, bool full_match = true)
{
using boost::spirit::qi::parse;
char const* f(input);
char const* l(f + strlen(f));
bool result1 = parse(f,l,endian_word_type,voxel);
bool result2 =((!full_match) || (f ==l));
if ( result1 && result2) {
//doing nothing, parsing data is pass to voxel alreay
} else {
std::cerr << "Error: not match!!" << std::endl;
exit(1);
}
}
typedef boost::uint16_t bs_int16;
typedef boost::uint32_t bs_int32;
int main ( int argc, char *argv[] ){
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
using qi::big_word;
using qi::big_dword;
boost::uint32_t ui;
float uf;
binary_parser("\x01\x02\x03\x04",big_word,ui); assert(ui=0x01020304);
binary_parser("\x01\x02\x03\x04",big_word,uf); assert(uf=0x01020304);
return 0;
}
I almost copy the example, but why this binary parser doesn't work. I use Mac OS 10.5.8 and gcc 4.01 compiler.
| The big_word parser matches a big-endian word (16 bits), while big_dword will match what you want (big-endian dword, 32 bits). But I don't think it to be a good idea to use a float as the attribute to the binary parser, you might not get what you expect.
|
2,870,214 | 2,870,296 | How do I add controls other than buttons/actions to toolbars in Qt, such as text boxes and combo boxes? | From the screenshot featured on this page http://www.kde.gr.jp/~ichi/qt/designer-manual-3.html it seems like this functionality was available in Qt3. Was it removed in Qt4?
| I don't believe you can do so from within Designer. You can add other widgets programmatically using QToolBar::addWidget().
|
2,870,301 | 2,870,320 | C++ pass enum as parameter | If I have a simple class like this one for a card:
class Card {
public:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
Card(Suit suit);
};
and I then want to create an instance of a card in another file how do I pass the enum?
#include "Card.h"
using namespace std;
int main () {
Suit suit = Card.CLUBS;
Card card(suit);
return 0;
}
error: 'Suit' was not declared in this scope
I know this works:
#include "Card.h"
using namespace std;
int main () {
Card card(Card.CLUBS);
return 0;
}
but how do I create a variable of type Suit in another file?
| Use Card::Suit to reference the type when not inside of Card's scope. ...actually, you should be referencing the suits like that too; I'm a bit surprised that Card.CLUBS compiles and I always thought you had to do Card::CLUBS.
|
2,870,377 | 2,870,413 | Is it possible to call an object method this way in C++? | Here's my class definition:
class A {
public:
void do_lengthy_work() {
cout << "working." << endl;
}
};
I have an object of type A, and I want to call do_lengthy_work() on it:
A a;
a.do_lengthy_work();
Is it also possible to call the same method using some variant of the following?
A::do_lengthy_work(a);
| You can wrap the function with mem_fun_ref:
mem_fun_ref(&A::do_lengthy_work)(a);
This can be very useful for STL algorithms like for_each:
std::vector<A> vec;
std::for_each(vec.begin(), vec.end(), mem_fun_ref(&A::do_lengthy_work));
If you have an A *, you would use mem_fun:
std::vector<A *> vecp;
std:for_each(vecp.begin(), vecp.end(), mem_fun(&A::do_lengthy_work));
|
2,870,493 | 2,870,651 | How does Photoshop (Or drawing programs) blit? | I'm getting ready to make a drawing application in Windows. I'm just wondering, do drawing programs have a memory bitmap which they lock, then set each pixel, then blit?
I don't understand how Photoshop can move entire layers without lag or flicker without using hardware acceleration. Also in a program like Expression Design, I could have 200 shapes and move them around all at once with no lag. I'm really wondering how this can be done without GPU help.
Also, I don't think super efficient algorithms could justify that?
| Look at this question:
Reduce flicker with GDI+ and C++
All you can do about DC drawing without GPU is to reduce flickering. Anything else depends on the speed of filling your memory bitmap. And here you can use efficient algorithms, multithreading and whatever you need.
|
2,870,529 | 2,889,601 | g++ How to get warning on ignoring function return value | lint produces some warning like:
foo.c XXX Warning 534: Ignoring return value of function bar()
From the lint manual
534 Ignoring return value of function
'Symbol' (compare with Location) A
function that returns a value is
called just for side effects as, for
example, in a statement by itself or
the left-hand side of a comma
operator. Try: (void) function(); to
call a function and ignore its return
value. See also the fvr, fvo and fdr
flags in §5.5 "Flag Options".
I want to get this warning, if there exists any, during compilation. Is there any option in gcc/g++ to achieve this? I had turned on -Wall but that apparently did not detect this.
| Thanks to WhirlWind and paxdiablo for the answer and comment. Here is my attempt to put the pieces together into a complete (?) answer.
-Wunused-result is the relevant gcc option. And it is turned on by default. Quoting from gcc warning options page:
-Wno-unused-result
Do not warn if a caller of a function marked with attribute warn_unused_result (see
Variable Attributes) does not use its return value. The default is -Wunused-result
So, the solution is to apply the warn_unused_result attribute on the function.
Here is a full example. The contents of the file unused_result.c
int foo() { return 3; }
int bar() __attribute__((warn_unused_result));
int bar() { return 5; }
int main()
{
foo();
bar(); /* line 9 */
return 0;
}
and corresponding compilation result:
$gcc unused_result.c
unused_result.c: In function ‘main’:
unused_result.c:9: warning: ignoring return value of ‘bar’, declared with attribute warn_unused_result
Note again that it is not necessary to have -Wunused-result since it is default. One may be tempted to explicitly mention it to communicate the intent. Though that is a noble intent, but after analyzing the situation, my choice, however, would be against that. Because, having -Wunused-result in the compile options may generate a false sense of security/satisfaction which is not true unless the all the functions in the code base are qualified with warn_unused_result.
|
2,871,055 | 2,871,067 | User Defined Class as a Template Parameter | I' m re-implementing std::map. I need to make sure that any data type (basic or user defined) key will work with it. I declared the Map class as a template which has two parameters for the key and the value. My question is if I need to use a string as the key type, how can I overload the < and > operators for string type keys only?? In template specialization we have to specialize the whole class with the type we need as I understand it.
Is there any way I can do this in a better way?? What if I add a separate Key class and use it as the template type for Key?
| You should factor out the comparison as a type, like the normal std::map does. That is, have a utility class less_compare:
template <typename T>
struct less_compare
{
bool operator()(const T& pLhs, const T& pRhs) const
{
return pLhs < pRhs;
}
};
And then:
template <typename Key, typename Value, typename Compare = less_compare<Key> >
class map
{
// ...
private:
Compare mCompare;
};
And to compare two values, do: if (mCompare(someThing, someOtherThing)), which will be true with someThing is "less than" someOtherThing. Note this factoring also allows user-defined comparisons (which is why "less than" is quoted). This is known as policy-based design.
And now you can specialize just the less_compare class for C-strings. (And also provide greater_compare and kin.)
Do keep in mind, unless this is for learning, you should not be implementing your own map. Also note that std::string has operator< overloaded already.
|
2,871,353 | 2,875,946 | how can udp data can passed through RS232 in ansi c? | i want to transmit and receive data on RS232 using udp and i want to know about techniques which allow me to transmit and receive data on a faster rate and also no lose of data is there?
thanx in advance. i have tried but need improvements if possible
#include <stdio.h>
#include <dos.h>
#include<string.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#define PORT1 0x3f8
void main()
{
int c,ch,choice,i,a=0;
char filename[30],filename2[30],buf;
FILE *in,*out;
clrscr();
while(1){
outportb(PORT1+0,0x03);
outportb(PORT1+1,0);
outportb(PORT1+3,0x03);
outportb(PORT1+2,0xc7);
outportb(PORT1+4,0x0b);
cout<<"\n===============================================================";
cout<<"\n\t*****Serial Communication By BADR-U-ZAMAN******\nCommunication between two computers By serial port";
cout<<"\nPlease select\n[1]\tFor sending file \n[2]\tFor receiving file \n[3]\tTo exit\n";
cout<<"=================================================================\n";
cin>>choice;
if(choice==1)
{
strcpy(filename,"C:\\TC\\BIN\\badr.cpp");
cout<<filename;
for(i=0;i<=strlen(filename);i++)
outportb(PORT1,filename[i]);
in=fopen(filename,"r");
if (in==NULL)
{ cout<<"cannot open a file";
a=1;
}
if(a!=1)
cout<<"\n\nFile sending.....\n\n";
while(!feof(in))
{
buf=fgetc(in);
cout<<buf;
outportb(PORT1,buf);
delay(5);
}
}
else
{
if(choice==3)
exit(0);
i=0;
buf='a';
while(buf!=NULL)
{
c=inportb(PORT1+5);
if(c&1)
{
buf=inportb(PORT1);
filename2[i]=buf;
i++;
}
}
out=fopen(filename2,"t");
cout<<"\n Filename received:"<<filename[2];
cout<<"\nReading from the port...";
cout<<"writing to file"<<filename2;
do
{
c=inportb(PORT1+5);
if(c&1)
{
buf=inportb(PORT1);
cout<<buf;
fputc(buf,out);
delay(5);
}
if(kbhit())
{
ch=getch();
}
}while(ch!=27);
}
getch();
}
}
| Be aware the many operating systems block direct access to ports. You would have to write a specialized driver to access them.
If you can control the RS232 port pins directly, you may be able to adjust the speed programmatically. In most cases, RS232 is controlled by a UART (or USART). This device also controls the speed (burst rate). The transmission speed is limited by this device. For example, if the UART's top supported speed is 9600 bps, then your program cannot transmit data any faster.
You will want to optimize your program to transmit as much content as possible per I/O transaction. This is the most efficient use of the communications channel. A common method for transmitting is to have one thread that transmits data from a buffer. The main thread formats the data into the buffer, then signals the transmission thread to start. This is similar to using a DMA controller. Also check if your port controller has block data capabilities, which make your program more efficient.
Hope this helps.
|
2,871,364 | 2,871,779 | Image rotate OpenCV error | When I use this code to rotate the image, the destination image size remains same and hence the image gets clipped. Please provide me a way/code snippet to resize accordingly (like Matlab does in imrotate) so that image does not get clipped and outlier pixels gets filled with all white instead of black. I don't want image to be scaled down to fit in original size. I just want rotation, no scaling.
void imrotate(std::string imgPath,std::string angleStr,std::string outPath) {
size_t found1,found2;
found1=imgPath.find_last_of('/');
found2=imgPath.size()-4;
IplImage* src=cvLoadImage(imgPath.c_str(), -1);;
IplImage* dst;
dst = cvCloneImage( src );
int angle = atoi(angleStr.c_str());
CvMat* rot_mat = cvCreateMat(2,3,CV_32FC1);
CvPoint2D32f center = cvPoint2D32f(
src->width/2,
src->height/2
);
double scale = 1;
cv2DRotationMatrix( center, angle, scale, rot_mat );
cvWarpAffine( src, dst, rot_mat);
char angStr[4];
sprintf(angStr,"%d",angle);
cvSaveImage(string(outPath+imgPath.substr(found1+1,found2-found1-1)+"_"+angStr+".jpg").c_str(),dst);
cvReleaseImage(&src);
cvReleaseImage(&dst);
cvReleaseMat( &rot_mat );
}
Original Image:
alt text http://freeimagehosting.in/images/185_ElectricalG.jpg
Rotated Image:
alt text http://freeimagehosting.in/images/638_ElectricalG_60.jpg
| Instead of cloning the source image as the dest you are going to have to create an image big enough to take the final rotated image, which will be a square with sides 1.5 times the biggest of the source width or height.
Edit:
The amount you need to enlarge the destination by is 1 + sin(angle of rotation), which has a maximum value at 45 degrees of 1.414... This must be rounded up to a suitable value
|
2,871,584 | 2,872,044 | Specialization of template method - what's wrong with my code? | What's wrong with this code?
class School {
public:
template<typename T> size_t count() const;
private:
vector<Boy*> boys;
vector<Girl*> girls;
};
template<> size_t School::count<Boy>() const {
return boys.size();
}
My compile says
error: specialization of ‘size_t School::count() [with T = Boy]’
after instantiation
Could you please help?
ps. This is how I'm going to use it later:
School s;
size_t c = s.count<Boy>();
| Have you accidentally called count<Boy> in School before it is declared? One way to reproduce your error is
class Boy;
class Girl;
class School {
public:
template<typename T> size_t count() const;
size_t count_boys() const { return count<Boy>(); }
// ^--- instantiation
private:
std::vector<Boy*> boys;
std::vector<Girl*> girls;
};
template<> size_t School::count<Boy>() const { return boys.size(); }
// ^--- specialization
int main () { School g; return 0; }
You need to move the definition of count_boys() after all template members are specialized.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.