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 |
|---|---|---|---|---|
823,003 | 823,014 | Have a C++ Class act like a custom ostream, sstream | I have a C++ class MyObject and I want to be able to feed this data like I would to a osstream (but unlike a direct sstream, have the incoming data be formatted a special way). I can't seem to figure out how to overload a operator for MyObject to eat input given to it.
class MyObject {
public:
ostringstream s;
... | try this:
class MyObject {
public:
template <class T>
MyObject &operator<<(const T &x) {
s << ':' << x << ':';
return *this;
}
std::string to_string() const { return s.str(); }
private:
std::ostringstream s;
};
MyObject obj;
obj << "Hello" << 12345;
std::cout << obj.to_string() <<... |
823,107 | 823,120 | What is wrong with this setup? | I created a program called test:
#include<stdlib.h>
#include<iostream>
int main()
{
std::cout<<system("..\\add\\debug\\add.exe 4 8");
while(true);
return 0;
}
add.exe consists of
#include<stdlib.h>
int main(int argc,char **argv[])
{
int n=((unsigned)argv[1]);
int m=((unsigned)argv[2]);
return(n... | The problem is that you are converting a pointer value into an integer. The arguments will be passed to your program as C style strings (const char*). You need to first convert these to a string using an API like atoi.
#include<stdlib.h>
int main(int argc,char *argv[])
{
int n= atoi(argv[1]);
int m= atoi(ar... |
823,116 | 823,132 | How do I use C++ STL containers in My iPhone App? | I'd like to use an STL set in my iPhone app (which is written in Objective-C in XCode). How do I include set and/or use the standard namespace?
In C++ I'd do this:
#include<set>
using namespace std;
// use the set<T> somewhere down here...
How can I do this in Objective-C?
| Just rename your source file so it ends in .mm and it should trigger the Objective-C++ front-end; you can then mix Objective-C and C++ in it. More information here.
|
823,283 | 823,303 | Is there a function that returns the character/string at a point in a .txt? | I know its possible to get a part of a .txt, then convert it to an integer, then store it in a variable, but is it possible to to that in a single declaration. (The variable needs to be global).
Ie:
[data.txt]
1020
[convert_data.cpp]
#include<fstream>
fstream convert("data.txt");
//way to declare something equal to A P... | No, you can't do it in a single declaration. You can write a function to do that, and then you can initialize local variables with that function, but you can't initialize global variables with it. If you want to initialize global variables, you'll need to explicitly do so during your program's initialization routine,... |
823,285 | 823,315 | What Are Some Quirks/Surprises with Using .mm Files in Objective-C? | I want to use some C++ STL collections in my Objective-C iPhone app. Apparently this is possible by giving files the extension ".mm" . What are some of the quirks/surprises associated with this?
I want to use the basic containers that I'm familiar with (vector, queue, set, ...)
Cheers!
| See Using C++ With Objective-C for a detailed list of what you can and can't do. You can do most things that you would expect. You just can't do things like have a C++ class inherit from an Objective-C class or vice-versa, you can't mix C++ exceptions with Objective-C exceptions, and C++ introduces several new keywor... |
823,345 | 823,359 | How can I make this declaration work? | EDIT: I also got an answer to make sector a vector of vectors:
vector<vector<char>>sector;
and that gets rid of the rest of my errors.
EDIT: I've made sector an array of pointers as someone suggested, and still get three errors:
EDIT: I have edited the program, but it has not fixed all of the errors:
I have this secti... | Well,
function load_data(int,int) returns a char.
You are passing that char to the atoi function, that takes a char*. In addition to that, you are probably not including stdlib.h header file!!
#include <cstdlib>
int atoi(const char*);
If you dont wan't to include stdlib.h, then you could declare atoi as extern, but ... |
823,426 | 823,455 | Passing references to pointers in C++ | As far as I can tell, there's no reason I shouldn't be allowed to pass a reference to a pointer in C++. However, my attempts to do so are failing, and I have no idea why.
This is what I'm doing:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfun... | Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:
string s;
string* _s = &s;
myfunc(_s);
should compile just fine.
However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itsel... |
823,479 | 823,525 | Multiple threads reading from the same file | My platform is windows vista 32, with visual c++ express 2008 .
for example:
if i have a file contains 4000 bytes, can i have 4 threads read from the file at same time? and each thread access a different section of the file.
thread 1 read 0-999, thread 2 read 1000 - 2999, etc.
please give a example in C language.
| If you don't write to them, no need to take care of sync / race condition.
Just open the file with shared reading as different handles and everything would work. (i.e., you must open the file in the thread's context instead of sharing same file handle).
#include <stdio.h>
#include <windows.h>
DWORD WINAPI mythread(LPV... |
823,553 | 823,828 | How to get hardware MAC address on Windows | I'm playing around with retrieving the MAC address from the NIC - there are a variety of ways to get it, this article covers the most common:
http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451
I'm currently using the GetAdaptersInfo method, which seems the most bulletproof, but if the MAC addr... | My guess is that in the linked CodeGuru article, the Miniport solution is likely to overcome the problem you describe, albeit painful to implement. The reason I think this is that I have used the GetAdaptersInfo solution myself in the past, and noticed that the MAC address will change without reboot when an adapter is... |
823,854 | 823,886 | How do I show command-line build options in Visual C++ 2008? | In a Visual C++ 2008 project, building a project will display following information in the output window:
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>Compiling...
1>main.cpp
1>test1.cpp
1>test2.cpp
1>Generating Code...
1>Linking...
1>LINK : test.exe not found or not built by the last ... | This is controlled via the "Suppress startup banner" setting in the "General" sub-tab of the "C/C++" tab in the project's property pages. If you set it to "No", it will show in the Output window the command line being used during compilation.
|
823,935 | 823,981 | What's the point in defaulting functions in C++11? | C++11 adds the ability for telling the compiler to create a default implementation of any of the special member functions. While I can see the value of deleting a function, where's the value of explicitly defaulting a function? Just leave it blank and the compiler will do it anyway.
The only point I can see is that a d... | A defaulted constructor will have a declaration, and that declaration will be subject to the normal access rules. E.g. you can make the default copy constructor protected. Without these new declarations, the default generated members are public.
|
823,971 | 824,013 | Is it possible to use boost.any as a key in a std::map(or something similiar)? | std::map<any, string> is not working so I wonder if there's another approach to
have arbritary keys?
| I think the issue is not with Boost::Any, but rather with the fact that you are not specifying a custom comparator. Since map is a sorted associative container, you need to have a comparator.
The following works for me: tailor it according to your purposes:
#include <iostream>
#include <map>
#include <boost/any.hpp>
u... |
824,143 | 824,191 | Working with string streams? | Say i have a stringsteam in C++, and I want to do different operations to it like:
Searching for a sequence of characters,
Converting block of text into int (in the middle of the line),
Moving the get pointer back and forth and so on.
What is the standard/common way of doing this kind of things with stringstreams?
| You can use stringstream::str() method which returns the associated std::string object. Then you can do your desired operations on the returned string.
|
824,160 | 824,261 | Which compilation option should be set for profiling? | I need to profile an application compiled with intel's compiler via VC++.
I'm using VTune to profile my code.
My understanding is that in release mode I won't have the debug information
that is necessary for the profiler to profile my code while in debug mode, the result
of the profiling will not be pertinent.
What sho... | You should certainly profile with optimisations enabled (compiler option /O3). /Zi is the Intel compiler switch (on Windows) to enabled debugging information.
Because of the optimisations, some functions may be missing from the debugging information due to inlining, but VTune will cope with that.
|
824,295 | 824,307 | What does C++ struct syntax "a : b" mean | If I have a C++ struct, defining a 64bit data word such as..
struct SMyDataWord
{
int Name : 40;
int Colour : 24;
};
What does the : 40 syntax mean... does it mean that the first 40 bits are reserved for the Name and the remaining 24 bits for the Colour?
This is how it appears to be being used, but I've not co... | Bitfields, carried over from C. Name is 40 bits wide, Colour is 24 bits wide. Your struct therefore has at least 64 bits. On my system 64 bits would be 8 bytes.
|
824,512 | 824,571 | Why are empty expressions legal in C/C++? | int main()
{
int var = 0;; // Typo which compiles just fine
}
| This is the way C and C++ express NOP.
|
825,015 | 825,083 | g++ rejects my simple functor with "expected a type, got 'xyz'" | I've been playing about with functors in C++. In particular, I've got a vector of pairs I'd like to sort by the first element of the pair. I started off writing a completely specialised functor (i.e. something like "bool MyLessThan(MyPair &lhs, MyPair &rhs)"). Then, just because this sort of stuff is interesting, I wan... | You need to specialize std::less with the comparison type you're using.
Pair1stFunc2<MyPair, std::less<int> >()
will do the trick. Within your own operator() you'll also need to instantiate an object of the comparison type, since you can't just call the class directly. E.g. change
return F(lhs.first, rhs.first);
to... |
825,018 | 825,365 | Pimpl idiom vs Pure virtual class interface | I was wondering what would make a programmer to choose either Pimpl idiom or pure virtual class and inheritance.
I understand that pimpl idiom comes with one explicit extra indirection for each public method and the object creation overhead.
The Pure virtual class in the other hand comes with implicit indirection(vtabl... | When writing a C++ class, it's appropriate to think about whether it's going to be
A Value Type
Copy by value, identity is never important. It's appropriate for it to be a key in a std::map. Example, a "string" class, or a "date" class, or a "complex number" class. To "copy" instances of such a class makes sense.
An ... |
825,935 | 826,008 | Derived Functor with any return type and any parameters | I have a class that uses functors as units of work. It accepts a reference to a functor in its Run() method. To allow this class to operate on any functor, all these functors must derive from my base functor class which looks like this:
class baseFunctor{
public:
virtual void operator()()=0;
virtual baseFuncto... | How will the class that calls the functor know what parameters to provide and what to do with the return value, if any?
|
826,354 | 830,365 | Rebind a socket to a different interface | Is there an existing Linux/POSIX C/C++ library or example code for how to rebind a socket from one physical interface to another?
For example, I have ping transmitting on a socket that is associated with a physical connection A and I want to rebind that socket to physical connection B and have the ping packets continue... | As of your updated post, the problem is that changing the routing info is not going to change the source address of your ping, it will just force it out the second interface. This answer contains some relevant info.
You'll need to change the ping program. You can use a socket-per-interface approach and somehow inform... |
826,569 | 826,635 | Compelling examples of custom C++ allocators? | What are some really good reasons to ditch std::allocator in favor of a custom solution? Have you run across any situations where it was absolutely necessary for correctness, performance, scalability, etc? Any really clever examples?
Custom allocators have always been a feature of the Standard Library that I haven't ha... | As I mention here, I've seen Intel TBB's custom STL allocator significantly improve performance of a multithreaded app simply by changing a single
std::vector<T>
to
std::vector<T,tbb::scalable_allocator<T> >
(this is a quick and convenient way of switching the allocator to use TBB's nifty thread-private heaps; see ... |
826,698 | 826,773 | How to make NUnit assertion failures show line numbers for C++? | When I run NUnit tests against my C++ code and an assertion fails, I don't get line numbers for where the failure occurs.
Sample Method:
[Test]
void testMethod()
{
Assert::Fail("test comment");
}
Sample output:
[nunit2] Failures:
[nunit2] 1) namespace.SomeTest.testMethod: test comment
[nunit2] at namespace.Som... | Double check that you are building your classes with Debug information (PDB).
The Assert framework basically throws an exception when the assert fails and the exception captures a StackTrace. The stack trace gets it's line numbers from the PDB file associated with the executable.
|
826,742 | 826,771 | What data type does memory see when I use void? | When I create a method of type int the compiler reserves X number of bits in memory. So how does the see a void type? How many bits/bytes does a void type take up?
| the void type does not take any bits. you cannot declare a variable of type void. this:
void a;
causes a compilation error.
void is just a place holder that means "nothing" a function that returns void returns nothing and a function that takes void as an argument, takes no arguments.
You can however declare a variable... |
826,870 | 826,874 | Why does my program consume 100% CPU under nVidia NView? | I was recently working on a windows program that would sometimes become unresponsive when scrolling through a large list of items in a production environment. Of course it works fine on my desktop. The production Environment is:
Windows XP based Workstation with 2 monitors
nVidia Video Drivers with nView enabled
Of n... | This is interesting because nView is a 3rd party DLL provided by NVidia. Postings on the internet about nview!NVLoadDatabase suggest that there is an unpatched defect in nview. This is supported by the fact that explorer uses 100% CPU, as confirmed by these reports. See: http://forums.nvidia.com/lofiversion/index.php?t... |
826,935 | 826,949 | How do I store arrays in an STL list? | Using C++ and the STL, does anybody know how to store integer arrays as nodes in an STL list or vector? I have an unknown number of pairs of numbers that I need to store, and coming from other languages my first thought was to use some sort of list- or vector-like data structure... but I'm running into some trouble. I ... | You can't store arrays in STL containers. You'd use a vector of vectors or somesuch for the general case. For your specific case, I'd use a vector of std::pair, like so: std::vector<std::pair<int, int> >. std::pair is a class that has two members, first and second, of whatever type you templatize it to be.
Edit: I o... |
827,010 | 827,158 | SQLite - pre allocating database size | Is there a way to pre allocate my SQLite database to a certain size? Currently I'm adding and deleting a number of records and would like to avoid this over head at create time.
| There is a hack - Insert a bunch of data into the database till the database size is what you want and then delete the data. This works because:
"When an object (table, index, or
trigger) is dropped from the database,
it leaves behind empty space. This
empty space will be reused the next
time new information i... |
827,016 | 827,050 | off-by-one error with string functions (C/C++) and security potentials | So this code has the off-by-one error:
void foo (const char * str) {
char buffer[64];
strncpy(buffer, str, sizeof(buffer));
buffer[sizeof(buffer)] = '\0';
printf("whoa: %s", buffer);
}
What can malicious attackers do if she figured out how the function foo() works?
Basically, to what kind of secu... | The only off-by-one error I see here is this line:
buffer[sizeof(buffer)] = '\0';
Is that what you're talking about? I'm not an expert on these things, so maybe I've overlooking something, but since the only thing that will ever get written to that wrong byte is a zero, I think the possibilities are quite limited. T... |
827,196 | 827,203 | Virtual Default Destructors in C++ | I've got a large set of inherited classes (criteria) which inherit from a base class (criterion). Here's criterion's code
class criterion
{
public:
virtual unsigned __int32 getPriorityClass() const = 0;
virtual BOOL include(fileData &file) const = 0;
virtual void reorderTree() = 0;
virtual unsigned int ... | Yes - the base class needs a virtual destructor, even if it's empty. If that is not done, then when something delete's a derived object through a base pointer/reference, the derived object's member objects will not get a chance to destroy themselves properly.
Derived classes do not need to declare or define their own ... |
827,393 | 827,422 | Default value for bool in C++ | I'm redesigning a class constructor in C++ and need it to catch an unspecified bool. I have used default values for all of the other parameters, but from my understanding bool can only be initialized to true or false. Since both of those cases have meaning in the class, how should I handle checking for change from a de... | The reality is that you can't do this. A bool has value, either true or false, and if you haven't initialized it then it is randomly true or false, possibly different at each run of the program or allocation of that class.
If you need to have a type with more options, define an enum.
typedef enum MyBool {
TRUE,
... |
827,552 | 827,572 | Why explicitly call a constructor in C++ | I know we can explicitly call the constructor of a class in C++ using scope resolution operator, i.e. className::className(). I was wondering where exactly would I need to make such a call.
| Most often, in a child class constructor that require some parameters :
class BaseClass
{
public:
BaseClass( const std::string& name ) : m_name( name ) { }
const std::string& getName() const { return m_name; }
private:
const std::string m_name;
//...
};
class DerivedClass : public BaseClass
{
public:... |
827,634 | 828,258 | Given a filename, how can I get the Adler32 using Crypto++ | Given a "string filename", how can I get the Adler32 checksum using the C++ Crypto++ library. I am a little confused about using their Source and Sink system.
Below I have the skeleton of the code that does MD5, but I can't seem to find any examples or tutorials on the Adler32 usage.
string filename = "/tmp/data.txt"
... | If you follow this http://www.cryptopp.com/wiki/HashFilter, you have to change hashMD5 for hashAdler32, and file_md5_digest for file_adler32_digest
Adler32 hashAdler32;
FileSource( filename.c_str(),
true,
new HashFilter( hashAdler32,
new HexEncoder( new StringSink( file_adler32_d... |
827,686 | 827,741 | Unmanaged lib in managed executable causing managed exceptions | I'm having a problem with mixing managed and unmanaged code. I have created two projects under a single solution in Visual Studio 2008 under Vista x64 SP1. One of them does not have CLR support and is a static library. My second project is compiled as an executable with CLR enabled. It depends on the first static libra... | The underlying exception is actually a Windows exception that the CLR is apparently turning into a CLR exception for you. You have an access violation. What you should be able to do is, in Visual Studio, head to Debug > Exceptions and break on acess violations. This should let you drop in and see where in the native co... |
827,706 | 827,725 | Calculating e^x without using any functions | We are supposed to calculate e^x using this kind of formula:
e^x = 1 + (x ^ 1 / 1!) + (x ^ 2 / 2!) ......
I have this code so far:
while (result >= 1.0E-20 )
{
power = power * input;
factorial = factorial * counter;
result = power / factorial;
eValue += result;
counter++;
iterations++;
}
My pro... | Both x^n and n! quickly grow large with n (exponentially and superexponentially respectively) and will soon overflow any data type you use. On the other hand, x^n/n! goes down (eventually) and you can stop when it's small. That is, use the fact that x^(n+1)/(n+1)! = (x^n/n!) * (x/(n+1)). Like this, say:
term = 1.0;
for... |
828,000 | 830,301 | Using SubclassDlgItem to change control types | I have a C++ MFC app with a dialog where I want to change the type of the control dynamically based on the selection in a combo box. The dialog resource starts off with a plain old edit control which I then call SubclassDlgItem on to change to a custom control type.
So far so good. Now, when the user changes the sele... | A colleague of mine suggested calling CWnd::LockWindowUpdate() before I do the switch. So, it boils down to something like this:
CRect r;
DWORD dwStyle = WS_CHILD|WS_TABSTOP|WS_VISIBLE;
m_pParent->GetDlgItem(m_nID)->GetWindowRect(&r);
m_pParent->ScreenToClient(r);
m_pParent->LockWindowUpdate();
m_pParent->InvalidateRe... |
828,067 | 828,202 | Pattern to specialize templates based on inheritance possible? | So, one problem pattern that I keep coming across and don't have a good solution for is how to provide template specializations that are based in what type a template parameter is derived from.
For example, suppose I have:
template<typename T>
struct implementPersist;
template<typename T>
void persist( T& object )
{
... | Yes, you can do this using enable_if.
#include <iostream>
#include <boost/type_traits.hpp>
using namespace std;
template <bool Enable, typename T = void>
struct enable_if
{
typedef T type;
};
template <typename T>
struct enable_if<false, T>
{
};
template <typename T, typename Enable = void>
struct persist_t {};... |
828,092 | 828,238 | Python-style integer division & modulus in C | In Python and Ruby, signed integer division truncates towards negative infinity, and signed integer modulus has the same sign the second operand:
>>> (-41) / 3
-14
>>> (-41) % 3
1
However, in C and Java, signed integer division truncates towards 0, and signed integer modulus has the same sign as the first operand:
pri... | The direction for rounding with signed integer division is not specified in older C standards. However, in C99 it is specified to round towards zero.
Here's portable code which works with all versions of the C standards and CPU architectures:
int py_div(int a, int b)
{
if (a < 0)
if (b < 0)
return -a / -b;... |
828,106 | 828,125 | Why is ClassName ClassName variable definition in C++ compiling and working properly? | Say I have a class definition:
class CustomClass {
int member;
};
Why is the following variable definition compiling and working correctly:
CustomClass CustomClass; // the variable is properly constructed
Should't this confuse the compiler and cause it to indicate an error?
| Class names and variable names occupy two separate namespaces. The compiler is able to figure out that the first CustomClass is a type and the second CustomClass is a variable name.
|
828,442 | 828,498 | Is there a way to compile-time assert if a variable is a class, struct or a basic type in c++? | I am trying to implement a template class that would be able to tell me if a variable is a class,structure or a basic type.
So far I've come with this:
template< typename T >
class is_class
{
private:
template< typename X >
static char ( &i_class( void(X::*)() ) )[1];
//
template< typename X >
stati... | is_class is a member of the Boost.Type_Traits library. The implementation is probably similar to what you already have. You would use in in conjunction with enable_if to create the function if appropriate:
template <class T>
typename enable_if_c<boost::is_class<T>::value>::type
foo() { }
Or the equivalent:
t... |
828,776 | 828,900 | comparison function of an associate container data member in class | I have a class like this:
class MyClass{
public:
MyClass(int Mode);
private:
std::map < int, std::string, CompFunc > data;
};
The data member must use different comparison function according to Mode argument.
if Mode == 1, then use CompFunc1.
if Mode == 2, then use CompFunc2.
etc.
but the CompFunc template ar... | struct Cmp
{
explicit Cmp(int mode) : mode_(mode) {}
bool operator()(int lhs, int rhs) const
{
switch (mode_)
{
case 1: return CompFunc1(lhs, rhs); break;
case 2: return CompFunc2(lhs, rhs); break;
// etc.
}
}
private:
int mode_;
};
clas... |
828,819 | 830,746 | Mystery: In Qt, why would editorEvent be called, but not createEditor? | I'm subclassing QAbstractItemDelegate. This is my code. Suggestions are welcome:
QWidget *ParmDelegate::createWidget(Parm *p, const QModelIndex &index) const {
QWidget *w;
if (index.column() == 0) {
w = new QLabel(p->getName().c_str());
} else {
if (p->isSection())
return NULL;... | From Qt's AbstractItemDelegate documentation:
To provide custom editing, there are two approaches that can be used. The first approach is to create an editor widget and display it directly on top of the item. To do this you must reimplement createEditor() to provide an editor widget, setEditorData() to populate the ed... |
828,880 | 828,915 | usage of virtual keyword with a class declaration | I was asked in an interview that what is the usage of virtual keyword with a class declaration in C++ and I answered that virtual keyword cannot be used with a class declaration in C++. The interviewer said that it is possible and asked me to test it later.
Now that I have checked it myself I have come to know that th... | That's a bug in VC++. Comeau and gcc both reject the code.
|
828,989 | 829,004 | Dump facility in C++ like var_dump() in PHP? | When I was in college i did some C/C++, but in near future i was working in PHP, and now I wish to put more time in learning C/C++.
In PHP i was using print_r() or var_dump() in order to display datas from structures or arrays. Do I have such a default functionality in C, in order to see what do i have in a struct or a... | There is no such functionality in C++. You can of course write your own Dump() functions. The reason such a feature cannot be generally provided is that the C++ compilation process removes the object metadata needed to structure the dump output. You can of course display structure contents in a debugger, where such me... |
829,311 | 1,091,972 | SQLGetDiagRec causes crash in Unicode release build | I'm having a problem with the call to SQLGetDiagRec. It works fine in ascii mode, but in unicode it causes our app to crash, and i just can't see why. All the documentation i've been able to find seems to indicate that it should handle the ascii/unicode switch internally. The code i'm using is:
void clImportODBCFile... | Well i found the correct answer, so I thought i would include it here for future reference. The documentation i saw was wrong. SQLGetDiagRec doesn't handle Unicode i needed to use SQLGetDiagRecW.
|
829,468 | 2,717,660 | how to perform boost::filesystem copy_file with overwrite | The Windows API function CopyFile has an argument BOOL bFailIfExists that allows you to control whether or not you want to overwrite the target file if it exists.
The boost::filesystem copy_file function has no such argument, and will fail if the target file exists. Is there an elegant way to use the boost copy_file f... | There's a third enum argument to copy_file, boost::filesystem::copy_option::overwrite_if_exists
copy_file(source_path, destination_path, copy_option::overwrite_if_exists);
https://www.boost.org/doc/libs/1_75_0/libs/filesystem/doc/reference.html
|
829,622 | 834,020 | How to insert a CLOB using OleDb | Could someone post some sample code showing how to insert text greater than 4000 characters in length into an Oracle 10g CLOB field?
I am using the Oracle OLEDB provider and ATL in C++.
My naive attempt returns the error 'ORA-01704: string literal too long' whenever the text I am attempting to insert goes over 4000 cha... | I eventually got this working.
In case anyone else has the same problem, I inserted the value EMPTY_CLOB() then used the ISequentialStream interface to stream the text into the empty field.
The Microsoft mydyntext sample shows how to do this.
|
829,623 | 831,857 | Determining the type of an expression | Sometimes I need to learn the type of an expression while programming in C or C++. Sometimes there's a good IDE or existent documentation to help me, but sometimes not. I often feel such a construct could be useful:
void (*myFunc)(int);
printf("%s", nameoftype(myFunc)); //"void (*)(int)"
int i, unsigned int u;
printf("... | What are you looking for? Automatic type inference or looking for the type so you can declare a variable correctly manually? (your own answers look like you want to have the second one). In this case, consider using Geordi:
<litb> make type pointer to function taking pointer to array of 10 int returning void
<geordi> v... |
829,625 | 829,751 | Winsock 2 portability | I'm about to develop some sockets related stuff in C++ and would like the software to be as portable between Windows and Linux as possible right from the start (making it portable later is tricky.)
I've looked at different libraries, there is one for C++ from alhem.net and of course there is boost::asio. boost::asio lo... | Winsocks aren't very compatible with Posix sockets:
In Winsocks a socket is of type SOCKET. On Posix it's simply a file descriptor (int), on which you can perform normal read() and write() calls.
They don't return errors the same way.
They don't support some options on recv() and send().
You have to initialize and uni... |
829,656 | 829,726 | C++ for Game Programming - Love or Distrust? | In the name of efficiency in game programming, some programmers do not trust several C++ features. One of my friends claims to understand how game industry works, and would come up with the following remarks:
Do not use smart pointers. Nobody in games does.
Exceptions should not be (and is usually not) used in game pr... | Look, most everything you hear anyone say about efficiency in programming is magical thinking and superstition. Smart pointers do have a performance cost; especially if you're doing a lot of fancy pointer manipulations in an inner loop, it could make a difference.
Maybe.
But when people say things like that, it's usua... |
829,700 | 829,923 | C++ new[] into base class pointer crash on array access | When I allocate a single object, this code works fine. When I try to add array syntax, it segfaults. Why is this? My goal here is to hide from the outside world the fact that class c is using b objects internally. I have posted the program to codepad for you to play with.
#include <iostream>
using namespace std;
... | One problem is that the expression s[i] uses pointer arithmetic to compute the address of the desired object. Since s is defined as pointer to a, the result is correct for an array of as and incorrect for an array of bs. The dynamic binding provided by inheritance only works for methods, nothing else (e.g., no virtua... |
829,792 | 830,203 | Expose Borland C++ methods to C# | I have following method in my Borland C++ code,
static bool UploadBitstream(void)
{
//Some code Implementation
}
And I'm trying to convert it to DLL and access it in C#.
What are the steps I need to follow to Convert the code DLL
and then use it in C# ??
| First, you have to make sure that the methods are defined extern. Then you need to declare the method stdcall or pascal calling convention, and mark them dllexport. See code listing below (this is ancient memory for me, so pardon if I am a bit off on modern Borland C++ compilers).
// code.h
extern "C" {
#define FUN... |
829,837 | 829,875 | How much one can do with (higher order) macros? | Is it "safe" to give macros names as arguments to other macros to simulate higher order functions?
I.e. where should I look to not shoot myself in the foot?
Here are some snippets:
#define foreach_even(ii, instr) for(int ii = 0; ii < 100; ii += 2) { instr; }
#define foreach_odd(ii, instr) for(int ii = 1; ii < 100; ii ... | If you're into using preprocessor as much as possible, you may want to try boost.preprocessor.
But be aware that it is not safe to do so. Commas, for instance, cause a great number of problems when using preprocessors. Don't forget that preprocessors do not understand (or even try to understand) any of the code they ar... |
829,919 | 829,937 | Delayed constructor in C++ | I have been reviewing some code that looks like this:
class A; // defined somewhere else, has both default constructor and A(int _int) defined
class B
{
public:
B(); // empty
A a;
};
int main()
{
B* b;
b = new B();
b->a(myInt); // here, calling the A(int _int) constructor,
//but default con... | That code does not call a's constructor. It calls A::operator()(int).
But if you explicitly call a constructor on an object that has already been constructed, you're well into undefined behavior-land. It may seem to work in practice, but there is no guarantee that it'll do what you expect.
|
830,067 | 830,747 | When should BOOL and bool be used in C++? | When should BOOL and bool be used in C++ and why?
I think using bool is cleaner and more portable because it's a built-in type. But BOOL is unavoidable when you interactive with legacy code/C code, or doing inter-op from .NET with C code/Windows API.
So my policy is:
Use bool inside C++.
Use BOOL when talk to outer wor... | Matthew Wilson discusses BOOL, bool, and similar in section 13.4.2 of Imperfect C++. Mixing the two can be problematic, since they generally have different sizes (and so pointers and references aren't interchangeable), and since bool isn't guaranteed to have any particular size. Trying to use typedefs or conditional ... |
830,119 | 830,134 | Garbage Collection in C++/CLI | Consider the below:
#include <iostream>
public ref class TestClass {
public:
TestClass() { std::cerr << "TestClass()\n"; }
~TestClass() { std::cerr << "~TestClass()\n"; }
};
public ref class TestContainer {
public:
TestContainer() : m_handle(gcnew TestClass) { }
private:
TestClass^ m_handle;
};
void... | ~TestClass()
declares a Dispose function.
!TestClass()
would declare a finaliser (the equivalent of C#'s ~TestClass) which gets called on a gc collection (although that's not guaranteed).
|
830,463 | 830,484 | What's the difference between global variables and variables in main? | MyClass GlobalVar;
int main()
{
MyClass VarInMain;
}
| A couple of things:
Typically, they're allocated in different places. Local variables are allocated on the stack, global variables are allocated elsewhere.
Local variables in main are only visible within main. On the other hand, a global variable may be accessed anywhere.
|
830,573 | 834,975 | Is it possible to narrow the friend relationship between classes and functions when multiple template types are involved? | Suppose I represent an image class as:
template <typename Pixel> class Image { ... };
I would need my own swap function to prevent extra copying of images, so I would need to make it a friend of Image. If inside Image I write:
template <typename T> friend void swap(Image<T>&, Image<T>&);
I get what I want, but it ma... | The only way I see this happening is defining the function inside the Image class, like so:
#include <iostream>
using std::cout;
template <typename Pixel>
struct image
{
template <typename KernelValue>
friend image<Pixel> convolve(image<Pixel> const&, image<KernelValue> const&)
{
cout << "foo\n... |
830,639 | 830,722 | A question about windows iocp | When I write a program about IO completion port in Windows Vista,
the first sample didn't work and the GetQueuedCompletionStatus() can not get
any OVERLAPPED structures.
So I put the OVERLAPPED structure in global scope,and it works amazingly.
Why is that?
CODE1:
int main()
{
OVERLAPPED o;
..
CreateIoCompl... | Okay! This is from the OVERLAPPED structure's MSDN page's Remarks section:
Any unused members of this structure should always be initialized to zero before the structure is used in a function call. Otherwise, the function may fail and return ERROR_INVALID_PARAMETER.
Globals are zero initializes whereas locals are not... |
830,674 | 830,783 | C++ Database Connectivity? | Hey, I want to know how to connect databases with C++? Any cross-platform solution which supports many databases? I know about SQLAPI++ but its a shareware... so any free one? What solutions do I have if I limit the OSes to Windows only?
Thanks
| SOCI - The C++ Database Access Library
|
830,708 | 830,917 | Is this program running Asynchronous or synchrounous? | When I run this program
OVERLAPPED o;
int main()
{
..
CreateIoCompletionPort(....);
for (int i = 0; i<10; i++)
{
WriteFile(..,&o);
OVERLAPPED* po;
GetQueuedCompletionStatus(..,&po);
}
}
it seems that the WriteFile didn't return until the writing job is done. At the same ... | If the file handle and volume have write caching enabled, the file operation may complete with just a memory copy to cache, to be flushed lazily later. Since there is no actual IO taking place, there's no reason to do async IO in that case.
Internally, each IO operation is represented by an IRP (IO request packet). It ... |
830,825 | 830,894 | How to capture standard error output from a Windows service? | I have an application that makes use of the Mozilla LDAP library. We're diagnosing a problem involving the LDAP library failing to make a connection to the server. I'm attempting to get additional information from the LDAP library by tossing a debug version of the lib in with the application and enabling debug using ld... | Can you try manually redirecting stderr?
FILE* stderr_redirect = freopen( "C:/stderr.log", "w", stderr );
// Code that writes to stderr
fclose( stderr_redirect );
Edit:
There is no way to redirect stdout or stderr for a service other than to handle those streams inside your service yourself. Some services... |
830,842 | 830,862 | Is there a way to get Visual Studio to unload dlls? | I have a Visual Studio 2008 project with some legacy native C++ DLL projects, and some newer WPF projects that use the DLLs. When I open the WPF xaml windows in the designer, Visual Studio loads up the native DLLs to be able to display the window.
The problem is, is that if I now need to make a change in the legacy ... | I've had similar problems. A little bit better than restarting is removing references to the dlls, then adding the references back in.
|
830,980 | 1,182,583 | VC2008 compiler errors opening sbr files (C2418 C1903 C2471) | EDIT: See my answer below for the hotfix.
ORIGINAL QUESTION:
In setting up for our boat-programming adventure I have to set up source control and fix project files for a team to use them. (the project was previously only being worked on by one person who took shortcuts with setting up the project includes, etc)
I am ... | Title: You may receive a "PRJ0008" or "C2471" or "C1083" or "D8022" or "LNK1103" or similar error message when you try to build a solution in Visual C++
Symptoms:
D8022 : Cannot open 'RSP00000215921192.rsp'
PRJ0008 : Could not delete file 'vc90.idb'.
C1083 : Cannot open program database file 'vc90.pdb'
C2471 : Cannot ... |
831,111 | 831,128 | Parsing a string in C++ | I'm trying to make a constructor for a graph class that accepts a string as a
parameter and uses it to build the graph.
The string is formatted as follows: |vertex list|Edges list|
e.g. |1,2,3,4,15|(1->2),(3->2),(4->15)|
The idea is that the constructor will take the values from the string and then
know to perform th... | You can use a stringstream and use the stream extraction operator to get your integers.
string s("12 34");
istringstream ss(s);
int x, y;
ss >> x >> y;
Since this is homework, I urge you to explore the possibilities and figure out the complete
code for yourself.
|
831,265 | 835,781 | I need a message pump that doesn't mess up my open window | My application (the bootstrap application for an installer that I'm working on needs to launch some other applications (my installer and third party installers for my installer's prerequisites) and wait for them to complete. In order to allow the GUI to do screen updates while waiting for an app to complete, I put a me... | I've also posted this question on the Microsoft forums, and thanks to the help of one Doug Harris at Microsoft, I found out my problem with my HWND and HMENU values was, indeed due to stale CWwnd* and CMenu* pointers (obtained using GetMenu() and GetDialogItem() calls. Getting the pointers again after launching the sec... |
831,394 | 831,506 | Build Process for a Visual C++ 2008 Express Project | I have a VS 2008 C++ project, with one very small and simple code file. I need to write an app to generate this file and build the project into a Win32 DLL. I will need to deliver a free compiler etc. with the app to my client, so I can't automate VS to do this.
How would I best go about this?
| VS 2008 Express installs the command line compiler (in fact the installer has an option so you only get the command line stuff). So getting a free compiler is no problem.
If you really only need to build a single file into a DLL, a cl command using the '/LD' option should be enough to do the trick (though you'll likely... |
832,031 | 832,081 | Cached or precomputed Immutable Functions in C# / C++ | By "immutable function" or "immutable method", I mean a function whose result will never vary if you give it the same arguments.
I would be interested to know if anyone know of a more generic or less verbose solution when you want to cache the precomputed value(s) of an immutable function.
Let me explain what I mean wi... | "Memoization" may be a useful term, here. There are a few memoization libraries out there (I could swear there was one in boost, but I can't find it at the moment). Doing a web search for "memoize" or "memoization" and your language of choice will reveal a few hits.
Here's a neat article in Wikibooks: Optimizing C++/... |
832,295 | 832,307 | How to retrieve foreign host's MAC address in C++ | Currently we're parsing arp request output from the command line.
string cmd = "arp -n ";
cmd.append(ipaddress);
cmd.append(" | grep ");
cmd.append(ipaddress);
fgets( line, 130, fp);
fgets( line, 130, fp);
ret.append(line);
...
It works, but is there a way to do this using a library function that wont depend so much ... | In general, this will depend on your OS. There's no real standard API for this.
Assuming you're on linux, open and parse /proc/net/arp. The format is similar to that of the output from the arp command. Note that you must send a packet to the IP in question at least once recently in order to have it in the ARP table, an... |
832,306 | 1,007,705 | Playing YouTube videos in a Windows Mobile application | I am working on an application for Windows Mobile 6 (or maybe 5) that plays YouTube videos. Well, it should play YouTube videos (and control/query the player about status changes, current frame/time, etc.)
After scouring the web for quite some time now (and a few trials), I still couldn't find a way to do this. The opt... | You can also grab YouTube videos as MP4, hopefully that expands your player options. You can look into DirectShow CF for playback functionality, or host some other player in your app that supports MP4 or FLV.
Trying to play it back through IE mobile won't work, as the version necessary of the Flash plug-in with video p... |
832,810 | 832,925 | Modern C++ Game Programming Examples | To what extent are modern C++ features like:
polymorphism,
STL,
exception safety/handling,
templates with policy-based class design,
smart pointers
new/delete, placement new/delete
used in game studios? I would be interested to know the names of libraries and the C++ features they use. For example, Orge3D uses al... | I've worked in 2 game companies, seen a number of codebases, and observed a number of debates on matters such as these among game developers, so I might be able to offer some observations. The short answer for each point is that it varies highly from studio to studio or even from team to team within the same studio. ... |
833,034 | 833,051 | How to convert const char* to char* | can any body tell me how to conver const char* to char*?
get_error_from_header(void *ptr, size_t size, size_t nmemb, void *data) {
ErrorMsg *error = (ErrorMsg *)data;
char* err = strstr((const char *)ptr,"550");
//error cannot convert const char** to char*
if(err) {
strncpy(error->data,(char*)p... | You don't appear to use err in the rest of that function, so why bother creating it?
if (NULL != strstr((const char *)ptr, "550"))
{
If you do need it, will you really need to modify whatever it points to? If not, then declare it as const also:
const char* err = strstr((const char *)ptr, "550");
Finally, as casts are... |
833,252 | 863,176 | Common C++ framework | Has anyone experienced with Common C++ Framework? Can it be used as a framework for a Telecom networking application?
| Why use that? Why use an obscure framework, when a well established, well documented, peer reviewed, high quality framework like Boost exists. It has good networking libraries among a million others.
|
833,257 | 837,204 | Controlling Lua5.1's garbage collector | OK so I have a C++ class that is exposed to Lua using SWIG. The script creates the object but a manager class also has a pointer to the object so it can be modified in C++(or another script) for whatever reason.
The problem is that when the script finishes the object is freed, how can I control what the Garbage collect... | Lua's GC only knows about references held within Lua, which is a reasonable implementation constraint. This implies that an object's lifetime is under Lua's control. If an object created by executing one script or function needs to be available to later scripts or functions, a reference to it has to be preserved within... |
833,258 | 833,270 | std::map unable to handle polymorphism? | When using std::map in c++, is it possible to store inherited classes as their "base class" in the map and still being able to call their overloaded methods? See this example:
#include <iostream>
#include <map>
class Base
{
public:
virtual void Foo() { std::cout << "1"; }
};
class Child : public Base
{
pub... | Polymorphism doesn't work in that case because the std::map stores the Base as a value type, so the objects get sliced.
If you want to have polymorphism on stored objects, you need to store pointers or use one of the boost ptr containers to effect the same. This means you need to remember to delete the memory afterward... |
833,289 | 833,333 | how do I use STL algorithms with a vector of pointers | I have a vector of pointers that are not owned by the container. How do I use algorithms on the targets of the pointers. I tried to use boost's ptr_vector, but it tries to delete the pointers when it goes out of scope.
Here is some code that needs to work:
vector<int*> myValues;
// ... myValues is populated
bool cons... | You could use Boost Indirect Iterator. When dereferenced (with operator*() ), it applies an extra dereference, so you end up with the value pointed by the pointer referenced by the iterator. For more information, you can also see this question about a dereference iterator.
Here's a simple example:
std::vector<int*> vec... |
833,291 | 833,308 | Is there an equivalent to WinAPI's MAX_PATH under linux/unix? | If I want to allocate a char array (in C) that is guaranteed to be large enough to hold any valid absolute path+filename, how big does it need to be.
On Win32, there is the MAX_PATH define. What is the equivalent for Unix/linux?
| There is a PATH_MAX, but it is a bit problematic. From the bugs section of the realpath(3) man page:
The POSIX.1-2001 standard version of this function is broken by
design, since it is impossible to determine a suitable size for the
output buffer, resolved_path. According to POSIX.1-2001 a buffer of
size PATH_MA... |
833,496 | 838,743 | Should managed code return an error or throw exceptions to unmanaged code? | I am about to expose a service written in C# to a legacy C++ application using COM. What is the best approach to report errors to the unmanaged client? Throwing exceptions or simply return an error value?
Thanks,
Stefano
| You should throw Exceptions. Exceptions are mapped to HRESULTS by the Framework, and HRESULTs are the standard way to return errors to COM clients, so this is the way to go.
Each Exception type has an HResult property. When managed code called from a COM Client throws an exception, the runtime passes the HResult to th... |
833,882 | 833,929 | Nested function calls order of evaluation | It's well-known that the order of evaluation of a function's arguments in unspecified and can differ between different compilers.
What doesn't seem so clear is whether function calls can be interleaved, in the following sense:
f(g(h()), i(j()))
Let's assume the compiler chooses to evaluate f's first parameter first. I... | The evaluation order is unspecified - see section 5.2.2/8 of the Standard:
The order of evaluation of arguments
is unspecified. All side effects of
argument expression evaluations take
effect before the function is entered.
|
834,179 | 834,250 | WTF does WTF represent in the WebKit code base? | I downloaded Chromium's code base and ran across the WTF namespace.
namespace WTF {
/*
* C++'s idea of a reinterpret_cast lacks sufficient cojones.
*/
template<typename TO, typename FROM>
TO bitwise_cast(FROM in)
{
COMPILE_ASSERT(sizeof(TO) == sizeof(FROM), WTF_wtf_reinterpret_cast_siz... | It’s short for Web Template Framework and provides commonly used functions all over the WebKit codebase.
|
834,314 | 834,362 | Should I declare all functions virtual in a base class? | When I declare a base class, should I declare all the functions in it as virtual, or should I have a set of virtual functions and a set of non-virtual functions which I am sure are not going to be inherited?
| A function only needs to be virtual iff a derived class will implement that function in a different way.
For example:
class Base {
public:
void setI (int i) // No need for it to be virtual
{
m_i = i;
}
virtual ~Base () {} // Almost always a good idea
virtual bool isDerived1 () // Is overridden... |
834,347 | 834,543 | VS2008 Express Editions and Resources | I am wanting to add resources (such as an icon) into a WinAPI based program in VC++ 2008 EE and am struggling. As there is no resource editor bundled with the IDE, is it possible?
My Google searches all seem to related to C# or other managed environments.
Thanks all,
| I'm afraid there is no resource editor with the Express Edition. (edit) I couldn't find a feature matrix on the official site, but Wikipedia says so, so it must be right;-)
You could look at 3rd party tools - a quick web search throws up ResEdit as a possible answer.
|
834,378 | 834,957 | Throw-catch cause linkage errors | I'm getting linkage errors of the following type:
Festival.obj : error LNK2019:
unresolved external symbol "public:
void __thiscall Tree::add(class Price &)"
(?add@?$Tree@VPrice@@@@QAEXAAVPrice@@@Z)
referenced in function
__catch$?AddBand@Festival@@QAE?AW4StatusType@@HHH@Z$0
I used to think it has to do wi... | Is there Tree.cpp? If there is, maybe you forgot to link it? Where is the implementation of Tree::add?
In addition I don't see where you call Tree::add. I guess it should be inside the try statement, right after the new?
Just a reminder:
For most compilers (i.e. those that practice separate compilation) the implementat... |
834,383 | 835,275 | C++11: a new language? | Recently I started reading (just a bit) the current draft for the future C++11 standard.
There are lots of new features, some of them already available via Boost Libs. Of course, I'm pretty happy with this new standard and I'd like to play with all the new features as soon as possibile.
Anyway, speaking about this dra... | In short, no, we can't consider this a new language. It's the same language, new features. But instead of being bolted on by using the Boost libs, they're now going to be standard inclusions if you're using a compiler that supports the 0x standard.
One doesn't have to use the new standard while using a compiler that su... |
834,622 | 834,631 | Best way to empty stringstream? | One of the possibilities is:
somestringstream.str("");
But is it most optimal? Is there any way to preserve stringstream internal buffer, so that following operator<<() calls would not require to reserve memory again?
| I've always done:
s.clear();//clear any bits set
s.str(std::string());
@litb gets into more detail about how to seekp to the start of the stream combined with std::ends you can keep your allocated size.
|
834,665 | 945,365 | Embedding Flash in 3D-rendering binary | I want to embed Flash (2D GUI) in my 3D game C++ application, and it must be portable. Rendering Flash is not enough, I need user action callbacks.
I found Hikari for Ogre3D, but I guess the technique it's based on only works on Windows? (It uses OLE.) Further, from what I've heard (unverified) CryEngine uses Flash.
Al... | Answering my own question: a colleauge recommended this library. Sounds free and interresting to me, think I'll look into it.
|
834,782 | 834,947 | Create tab blinking effect (like IM programs) using wxNotebook | How can I Create Tab blinking effect like IM programs do using wxNotebook?
A good example of this is would be any tabbed IM program that blinks to show the user that they received a new IM.
| You can give each tab an icon (using SetPageImage if i remember correctly). I did that in the past to show some progress bar. You could use it to draw a bitmap (wxMemoryDC) every time your timer triggers and update that image.
You can also use wxAuiNotebook. It doesn't use native widgets, but it's part of the AUI fram... |
834,848 | 835,035 | Problem with desktops | I have this code:
#define _WIN32_WINNT 0x0500
#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
Sleep(500);
HDESK hOriginalThread;
HDESK hOriginalInput;
hOriginalThread = GetThreadDesktop(GetCurrentThreadId());
hOriginalInput = Open... | You can pick which desktop to start an application in when the application starts.
STARTUPINFO si = {0};
si.cb = sizeof(STARTUPINFO);
si.lpDesktop = L"winsta0\\Default";
Then pass this struct into CreateProcess or CreateProcessAsUser.
You can also pick which session to start the application in (Enable the session ID ... |
834,865 | 834,916 | Avoid Deadlock using Non-virtual Public Interface and Scoped Locks in C++ | I've run into a problem which seems troubling to me. It seems I've found a situation that's easy enough to work-around, but that could lead to problems if a) I have a lapse in concentration while programming or b) somebody else starts implementing my interfaces and doesn't know how to handle this situation.
Here's my ... | Using private inheritance will potentially solve your problem:
class Foo
{
public:
void A( )
{
ScopedLock lock( mutex );
aImp( );
}
void B( )
{
ScopedLock lock( mutex );
bImp( );
}
protected:
virtual void aImp( ) = 0;
virtual void bImp( ) = 0;
};
class FooMiddle : priva... |
835,038 | 838,219 | Visual C++ Debug window displaying of CR/LF in Visual Studio 2008 | For some time now when I am debugging Visual C++ applications and viewing any CString or char* (or any other ascii char based type) variable in the Local, Auto, or Watch debug windows, the CR/LF characters in my variables are not displayed at all.
In other words, if I have a string variable set to "This is a line\r\nTh... | This seems to be some sort of hard-to-reproduce bug (I'm not seeing them in 2k8 either) according to this old link:
If we wanted to do this properly we'd need to issue the proper escape sequences for these characters. eg show "\r\n" in the string. The behavior of stripping special characters historical and will be fix... |
835,201 | 835,744 | What embedded browser for C++ project? | Is there any browser I could embedd in C++ application on Windows?
I need all features typical browser has (HTTP client, cookies support, DOM style HTML parser, JavaScript engine) except rendering.
Because I don't need rendering capability (and that's rather big part of a browser) I would prefer a browser with non mono... | I'm a bit confused by your question regarding embedding a web browser for which you don't need rendering capabilities. A web browser is rendering web pages by definition, unless you just need HTTP and XML with JavaScript capabilities which is a subset of a browser functionalities?
If you need a web browser to embed i... |
835,233 | 835,257 | How to handle passing runtime-sized arrays between classes in C++ | Right now I have a simple class that handles the parsing of XML files into ints that are useful to me. Looks something like this:
int* DataParser::getInts(){
*objectNumbers = new int[getSize()];
for (int i=0;i<getSize();i++){
objectNumbers[i]=activeNode->GetNextChild()->GetContent();
}
retur... | Part of the problem is that you are not pairing new[] with delete[]. This probably isn't the root of your bug here but you should get in the habbit of doing this.
The bug is almost certainly related to the code that you left commented out. Can you add some more context there so we can see what you're doing with the... |
835,236 | 835,278 | Bug in Array initialization in Managed C++ (followup) | Following up from my previous question.
Can anyone explain why the following code compiles without any errors:
typedef array<VdbMethodInfo^> MethodArray;
typedef array<VdbParameterInfo^> ParameterArray;
ParameterArray^ parameters = gcnew ParameterArray {
gcnew VdbParameterInfo("name", "string", "Paul")};
MethodArra... | I've found a workaround which makes the syntax cleaner anyway. I use the "..." syntax (Managed C++ equivalent to the C# "params" keyword"):
public ref class MetaData
{
typedef array<VdbMethodInfo^> MethodArray;
typedef array<VdbParameterInfo^> ParameterArray;
static ParameterArray^ params(... ParameterArray... |
835,324 | 835,377 | Migrating from old Borland C++ to Visual C++ Express | At the risk of appearing a dinosaur, I have some old C++ code, compiled with Borland C++, which sets registers, and interfaces to an Assembler module, which I would like to modernize. I have just installed MS VC++ Express, and needless to say a lot of things don't work! The default seems to be Win32, which is fine, so... | A couple of specific things from your example:
VC doesn't like _Export at all.
the anachronism is that you have modifiers (like __stdcall) on a data declaration. If <modname> doesn't have parens it's a data declaration and the modifiers don't do anything. If <modname> is a function implemented in assembly, you shoul... |
835,419 | 837,017 | MFC CDialog::Create fails | I'm having problems with some code to create a CDialog based window. The code was working fine last week. The only changes I made was replacing a C++ deque with a hash array. I had commented out the line of code with the Create method being called to allow me to skip loading the window. Now the code doesn't create ... | The problems seems to have been with the call to CDynLinkLibrary().
I had commented this out at the request of the company that writes the software that is loading my plugin. Adding this line back in caused some values to still be null, but the window is now created properly.
I'm going to do a bit of research on this ... |
835,590 | 835,629 | How would std::ostringstream convert to bool? | I stumbled across this code.
std::ostringstream str;
/// (some usage)
assert( ! str );
What does ostringstream signify when used in a bool context?
Is this possibly an incorrect usage that happens to compile and run?
| It tells you if the stream is currently valid. This is something that all streams can do. A file stream, for example, can be invalid if the file was not opened properly.
As a side note, this functionality (testing a stream as a bool) is achieved by overloading explicit operator bool in C++11 and later and by overloadi... |
835,617 | 836,026 | Hierarchical Memory allocator library for C++ | My application is mostly organised in layers so I found that something like the APR memory pools would be the best way.
While reading on SO about C++ placement new posts here & here, and a more generic C allocation question I was thinking about hand-crafting a hierarchical pool allocator as suggested in one post, but i... | I know of another good hierarchical memory allocator, but it calls malloc underneath the covers.
talloc is a hierarchical pool based memory allocator with destructors. It is the core memory allocator used in Samba4, and has made a huge difference in many aspects of Samba4 development.
To get started with talloc, I wo... |
835,642 | 836,001 | How can I delete a Win32 desktop with running programs, and terminate those programs? | I have this code:
#define _WIN32_WINNT 0x0500
#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
HDESK hOriginalThread;
HDESK hOriginalInput;
hOriginalThread = GetThreadDesktop(GetCurrentThreadId());
hOriginalInput = OpenInputDesktop(0, ... | If you want to force termination of a program that you started with CreateProcess (as in the code you posted), then you can just use TerminateProcess on the handle returned in your PROCESS_INFORMATION struct.
If you want to terminate all processes with threads attached to your new desktop, whether you started them or n... |
835,893 | 836,657 | OpenMP parallelization on a recursive function | I'm trying to use parallelization to improve the refresh rate for drawing a 3D scene with heirarchically ordered objects. The scene drawing algorithm first recursively traverses the tree of objects, and from that, builds an ordered array of essential data that is needed to draw the scene. Then it traverses that array m... | Here's a modified piece of pseudo-code that should work.
populatearray(thescene)
{
recursivepopulatearray(thescene)
#pragma omp parallel for
for each element in array
populate array element based on associated object
}
recursivepopulatearray(theobject)
{
for each childobject in theobject
{
assign a... |
835,914 | 836,666 | Qt: adapting signals / binding arguments to slots? | Is there any way to bind arguments to slots ala boost::bind?
Here's a for-instance. I have a window with a tree view, and I want to allow the user to hide a column from a context menu. I end up doing something like:
void MyWindow::contextMenuEvent (QContextMenuEvent* event) {
m_column = view->columnAt (event->x())... | AFAIK the only way is to create a QSignalMapper object to do this. It's like an extra level of indirection that can be used to generate a new signal providing the column index. It's a little bit clumsy IME, you can end up with lots of QSignalMapper objects hanging around all the time, but seems to be the best way at t... |
835,922 | 835,928 | What determines what is written to a C++ pointer when delete is called? | I have a pointer to a given class. Lets say, for example, the pointer is:
0x24083094
That pointer points to:
0x03ac9184
Which is the virtual function table of my class. That makes sense to me. In windbg, everything looks correct.
I delete said pointer. Now at 0x24083094 is:
0x604751f8
But it isn't some random garbag... | Nothing in the standard determines what gets written there. Visual studio (at least in debug mode) will often write sentinal values all over the place to help in catching bugs early.
This value is not something you can rely on, but if you ever find that value popping up in your program mysteriously, you can assume tha... |
836,327 | 836,879 | Stripping Down VS 2008 Win32 DLL to one file | I have a VS generated C++ Win32 DLL project. It has the following files:
stdafx.h
targetver.h
myProject.h
dllmain.cpp
myProject.cpp
stdafx.cpp
I can remove targetver.h, and merge dllmain.cpp into myProject.cpp. What more can I do to get the simplest file structure, preferably one file. I need to dynamically emit thi... | If you want a minimalistic file structure, you could just create the files yourself. Start an empty project, or delete all the files. Heck, just make a folder, write main.cpp, and compile it from the command line with cl.
Few IDEs really try to minimize files like you're trying to -- but when you create the project, yo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.