boost::multi_index_container crashes with _com_ptr_t objects - c++

I try to use boost::multi_index_container with _com_ptr_t objects.
Code compiles with no warnings but crashes in runtime.
Standard containers (std::set, map etc) work perfectly with such objects.
Is it possible to use multi_index_container with _com_ptr_t?
Sample code here:
#include "stdafx.h"
#include <boost\multi_index_container.hpp>
#include <boost\multi_index\random_access_index.hpp>
#include <boost\multi_index\global_fun.hpp>
#include <boost\multi_index\ordered_index.hpp>
#import "C:\Windows\SysWOW64\msxml6.dll" exclude("ISequentialStream", "_FILETIME")
using CTest =
boost::multi_index_container<MSXML2::IXMLDOMDocument2Ptr,
boost::multi_index::indexed_by<boost::multi_index::random_access<>>>;
int main()
{
::CoInitialize(nullptr);
CTest tst;
MSXML2::IXMLDOMDocumentPtr doc;
doc.CreateInstance(CLSID_DOMDocument);
tst.push_back(std::move(doc)); <-- crash here
::CoUninitialize();
return 0;
}

I notice that the multi_index_container you've defined holds pointers of type MSXML2::IXMLDOMDocument2Ptr, yet doc is of type MSXML2::IXMLDOMDocumentPtr (without the 2). I'm assuming this is OK, as the problem is really not related to this discrepancy.
Boost.MultiIndex does support move semantics, so you can use std::move as you please.
The actual problem is that _com_ptr_t has a weird, destructive operator& overload returning a pointer to the wrapped interface. This confuses the internal code of Boost.MultiIndex. You can easily bypass this overload as follows:
#include <boost\multi_index_container.hpp>
#include <boost\multi_index\random_access_index.hpp>
#include <boost\multi_index\global_fun.hpp>
#include <boost\multi_index\ordered_index.hpp>
#import "C:\Windows\SysWOW64\msxml6.dll" exclude("ISequentialStream", "_FILETIME")
struct IXMLDOMDocument2Ptr:MSXML2::IXMLDOMDocument2Ptr
{
using MSXML2::IXMLDOMDocument2Ptr::IXMLDOMDocument2Ptr;
IXMLDOMDocument2Ptr* operator&(){return this;}
const IXMLDOMDocument2Ptr* operator&()const{return this;}
};
using CTest =
boost::multi_index_container<IXMLDOMDocument2Ptr,
boost::multi_index::indexed_by<boost::multi_index::random_access<>>>;
int main()
{
::CoInitialize(nullptr);
{
// defined in scope so that destruction happens before CoUninitialize
CTest tst;
MSXML2::IXMLDOMDocumentPtr doc;
doc.CreateInstance(CLSID_DOMDocument);
tst.push_back(std::move(doc));
}
::CoUninitialize();
return 0;
}
Would you mind entering a ticket for this problem at Boost Trac? I can fix the issue internally (by not relying on user-overloadable operator&s) but it's going to take a while till I find the time to do so and I wouldn't like to forget about it.
Postscript
If you have this problem throughout your program, you can automate the fix as follows:
#include <boost\multi_index_container.hpp>
#include <boost\multi_index\random_access_index.hpp>
#include <boost\multi_index\global_fun.hpp>
#include <boost\multi_index\ordered_index.hpp>
#import "C:\Windows\SysWOW64\msxml6.dll" exclude("ISequentialStream", "_FILETIME")
template<typename CComPtr>
struct CFixedAddressofComPtr:CComPtr
{
using CComPtr::CComPtr;
CFixedAddressofComPtr* operator&(){return this;}
const CFixedAddressofComPtr* operator&()const{return this;}
};
template<typename CComPtr,typename TIndexList>
using CComPtrMultiIndexContainer=boost::multi_index_container<
CFixedAddressofComPtr<CComPtr>,
TIndexList
>;
using CTest =
CComPtrMultiIndexContainer<MSXML2::IXMLDOMDocument2Ptr,
boost::multi_index::indexed_by<boost::multi_index::random_access<>>>;
int main()
{
::CoInitialize(nullptr);
{
// declared in scope so that destruction happens before CoUninitialize.
CTest tst;
MSXML2::IXMLDOMDocumentPtr doc;
doc.CreateInstance(CLSID_DOMDocument);
tst.push_back(std::move(doc));
}
::CoUninitialize();
return 0;
}

Related

Unable to call member functions

I'm pretty sure I'm probably doing something stupid, but I've been at this an hour and a half and can't figure out what I'm missing.
I can create an object from my class using the default constructor, but can't use an overloaded constructor when I add one. I can't call the print member function that I have included or any others that I have tried to include either. I have put the three files into a Code::Blocks project and gotten the same result. I have also tried the three files on Dev-Cpp with the same result. Any help would be greatly appreciated.
Main Function
#include <iostream>
#include "Appt.h"
using namespace std;
int main()
{
Appt a();
a.print();
}
Appt.h
#ifndef APPT_H
#define APPT_H
#include <iostream>
#include <string>
using namespace std;
class Appt
{
public:
Appt();
void print();
private:
string description;
};
#endif // APPT_H
Appt.cpp
#include "Appt.h"
using namespace std;
Appt::Appt()
{
description = "No Description";
}
void Appt::print()
{
cout << description << endl;
}
I am using Code::Blocks 16.01 with the GCC compiler. These files are not currently in a project. I am also running Windows 7.
It looks like your problems may be related to this line:
Appt a();
Unfortunately, while this looks like it calls the default constructor, it actually declares a to be of type Appt(), that is, a function taking no arguments and returning Appt. If you want to call the default constructor, there are a few options:
Appt a;
Appt a = Appt();
Appt a{}; // requires C++11
I would prefer the last one.

Passing 0 to the shared pointer with deleter as the first argument

I'm readin Scott Meyrse C++ and now I'm at the section about deigning interfaces. The following code is supposed to be invalid:
std::tr1::shared_ptr<Investment> // attempt to create a null
pInv(0, getRidOfInvestment); // shared_ptr with a custom deleter;
// this won’t compile
He gave the following explanation:
The tr1::shared_ptr constructor insists on its first parameter being a
pointer, and 0 isn’t a pointer, it’s an int. Yes, it’s convertible to
a pointer, but that’s not good enough in this case; tr1::shared_ptr
insists on an actual pointer.
I tried similar example myself http://coliru.stacked-crooked.com/a/4199bdf68a1d6e19
#include <iostream>
#include <memory>
struct B{
explicit B(void *){ }
};
void del(int*){ }
int main()
{
B b(0);
std::shared_ptr<int*> ptr(0, del);
}
and it compiles and runs fine even in spite of passing 0 as the first argument.
What did he mean actually? Isn't that relevant already?
One is from #include <tr1/memory>; the other is from #include <memory>. There is a difference:
http://coliru.stacked-crooked.com/a/f76ea0ef17227d9d
#include <iostream>
#include <tr1/memory>
#include <memory>
struct B{
explicit B(void *){ }
};
void del(int*){ }
int main()
{
B b(0);
std::tr1::shared_ptr<int*> ptr(0, del);
std::shared_ptr<int*> ptr2(0, del);
}
It gives the error for the tr1 version but not the current standard version.

Using Boost::iostreams dual-use filters

I was attempting to follow the example of Finite State Filters in the Boost::iostreams documentation. However when I went to use the filter I got an error stating the ::imbue was not accessible because 'boost::iostreams::detail::finite_state_filter_impl' uses 'protected' to inherit from 'my_fsm'.
Frustrated I copied my code into the tests used to in the boost examples. The tests compile and pass. My conculsion is that I am probably mis-using the dual use filter defined by:
typedef io::finite_state_filter my_fsm_filter;
I feel that just pushing it onto a filtered_stream may not be proper, but I could not find a missing step. I am sure there must be a need to wrap the filter but I can find no example (though I am sure if I dug deep enough into the code used to test the boost code it has to be there somewhere).
here is a bit of example code:
#include <boost/mpl/vector.hpp>
#include <libs/iostreams/example/finite_state_filter.hpp>
namespace io = boost::iostreams;
struct my_fsm : io::finite_state_machine<my_fsm> {
BOOST_IOSTREAMS_FSM(my_fsm) // define skip and push.
typedef my_fsm self;
static const int beginline = 0;
static const int skipline = 1;
static const int dataline = 2;
typedef boost::mpl::vector <
row<beginline, is<'C'>, skipline, &self::skip>,
row<beginline, is_any, dataline, &self::push>,
row<skipline, is<'\n'>, beginline, &self::skip>,
row<skipline, is_any, skipline, &self::skip>,
row<dataline, is<'\n'>, beginline, &self::push>,
row<dataline, is_any, dataline, &self::push>
> transition_table;
};
typedef io::finite_state_filter<my_fsm> my_fsm_filter;
#include <iostream>
#include <string>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;
int main() {
io::stream<io::file_sink> out(io::file_sink("outputfile.txt"));
io::filtering_istream in;
my_fsm_filter infsm;
in.push(my_fsm_filter());
in.push(io::file_source("inputdata.txt"));
while (in) {
std::string line;
if(std::getline(in, line)) {
//std::cout << line << std::endl;
out << line << std::endl;
}
}
return 0;
}
I personally feel that there is a bug in the sample header with respect to this imbue call.
However, you can work around it by changing the typedef to
struct my_fsm_filter : io::finite_state_filter<my_fsm> {
using io::finite_state_filter<my_fsm>::imbue;
};
This explicitly exposes the imbue method as public on the derived type. I haven't looked at the sample program that you reported to be working (because you didn't link to it). But it's possible they used a similar hack.
In my tests, a similar edit to finite_state_filte.hpp L278 to add
using base_type::imbue;
to class finite_state_filter has the same effect.

Boost::Variant and function_types in it: How to put functions into Boost::variant?

Lyrics:
I try to implement a task pool over MPI. So I need some kind of RPC but one that would work between different parts of my program, meaning processor A wants processor B to call function C with argument D. We can not pass pointers to functions between processes like we do with threads, so we need some wrapper container to hold our function pointers at each process instance. All inside one source file\one program... So I started wondering about How to store functional objects with different signature in a container. My API Idea back then was wrong - it is better to define all functions in function pool at that pool construction (at least it shall be much easier to implement). But while implementing I faced next trouble:
Problem:
Such simple code (function_types, mpl::vector, variant):
#include <boost/function_types/function_type.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/variant.hpp>
#include <iostream>
#include <string>
template <class T>
int append(T val)
{
std::cout << "hello";
return 0;
}
int main()
{
boost::variant<boost::function_types::function_type< boost::mpl::vector<int,int> >::type , boost::function_types::function_type< boost::mpl::vector<int,std::string> >::type > a;
return 0;
}
Will not compile falling with:
Error 1 error C2066: cast to function type is illegal c:\program files\boost\include\boost\variant\variant.hpp 1231 1
And looking at source we see:
this code block:
variant()
{
// NOTE TO USER :
// Compile error from here indicates that the first bound
// type is not default-constructible, and so variant cannot
// support its own default-construction.
//
new( storage_.address() ) internal_T0();
indicate_which(0); // zero is the index of the first bounded type
}
So I wonder: How to get around this error?
Also I tried:
#include <boost/function_types/function_type.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/variant.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <string>
template <class T>
int append(T val)
{
std::cout << "hello";
return 1;
}
int main()
{
boost::variant< boost::function<int (std::string) >, boost::function<int (int) > > a;
a= &append<int>;
return 0;
}
Which fails with:
Error 1 error C2668: 'boost::detail::variant::make_initializer_node::apply<BaseIndexPair,Iterator>::initializer_node::initialize' : ambiguous call to overloaded function c:\program files\boost\include\boost\variant\variant.hpp 1330
Any Ideas on how to make boost.variant hold functions?
Of course we can play with shared pointers to functors like so:
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <string>
template <class in, class out>
struct s_append
{
out operator()(in val) {
std::cout << "hello";
return out();
}
};
int main()
{
boost::variant<boost::shared_ptr<s_append<int, int> >, boost::shared_ptr< s_append<std::string, int> > > a;
boost::shared_ptr<s_append<int, int> > b(new s_append<int, int> );
a=b;
return 0;
}
and it would compile but resulting API sucks - you have to 1) create functors for all functions you want to use (meaning limit there use of current process scope); 2) use shared_pointers and so I don't really even get how to call functions nested that way (simple first guess (*a)(22); just won't compile =( and API starts to be as bad as we would have using Boost.Any).
Try inserting a dummy type as the first argument of the variant. As the comment you found explains, only the first type in the variant is used for the variant's own default constructor. You could use an empty struct type for this (struct NoFunction {};).
That said, you may have been onto something with the idea to use boost::functions as the types in the variant...they are default-constructible at least. I'm not sure what the other error you had from that approach was caused by, but just wanted to let you know you could pursue that angle more if you can't use the dummy-type workaround I mentioned.

Does std::map<key, data> in C++ support native data types like Structures?

How do I map a key to a native data type like structure?
I wrote this snipped but I couldn't compile it. Do you have any ideas on how to fix it?
#include <map>
#include <iostream>
typedef struct _list
{
int a,b;
}list;
map<int,list> test_map;
int main(void)
{
cout <<"Testing"<< endl;
}
map resides in the std:: namespace. Two possible ways to fix this:
using namespace std;
// ...
map<int, list> test_map;
or
std::map<int, list> test_map;
I prefer the second method, but it's a purely personal choice.
On a related note, there is no real limitation on what you can put in a map, aside from the fact that they must be copyable/assignable, and that the key type must have a < operator (or you can also provide a comparer functor).
EDIT: Seems like <list> is included somewhere, either in <iostream> (unlikely) or <map> (strange but not impossible). A using namespace std will cause std::list to clash with your own struct. The solution: rename your struct, or remove the using namespace and put std:: where it's needed.
Added std where required.
Renamed list to mylist to avoid clash with std::list. Avoid typenames and variable names that clash with common usage.
Now compiles OK in VS2008.
#include <map>
#include <iostream>
typedef struct _list
{
int a,b;
} mylist;
std::map<int,mylist> test_map;
int main(void)
{
std::cout <<"Testing"<< std::endl;
return 0;
}
There's no issue with using your struct in the STL containers provided it's copyable cleanly (copy constructor), assignable (implements operator=) and comparable (implements operator<).
A number of problems here:
You're missing either a using::std or std::map, so the compiler doesn't know what map<int,list> means.
Assuming you have a using namespace std declaration, your typedef list might collide with the STL collection of the same name. Change the name.
Your typedef struct _tag {...} tag; construct is an archaic holdover from the 80's. It is not necesarry, and frankly rather silly. It gets you nothing.
Here's your code fixed:
#include <map>
#include <iostream>
struct MyList
{
int a,b;
};
std::map<int,MyList> test_map;
int main(void)
{
std::cout <<"Testing"<< std::endl;
return 0;
}
map<int, _list> test_map; or don't use list(much better) as a name of structure. (You probably also have
#include <list>
...
using namespace std;
somewhere in your code.
I would try to avoid using codepad at all.
I have done a couple of tests with your code and it seems that
it is adding an implicit (and unwanted) using namespace std --it does not require you to qualify map, cout or endl.
it is (probably) including more standard headers than you might want, including #include <list>.
That means that when the compiler looks at the code it is seeing two list, your version and the one in std. Because of the using directive, both are in scope in the line where you create the map and the compiler is not able to determine which to use.
Two simple things that you can do: change the name of your type for the simple test to something other than list (ouch! the tool forcing your naming choices!) or fully qualify the use:
#include <map>
struct list {
int a,b;
};
std::map< int, ::list > the_map;
// ...
Note that codepad is adding the include by itself and the using directive, so it will also compile:
struct list {
int a,b;
};
map<int,::list> the_map;
But that piece of code is wrong
You seem to be comming from C. Try this:
#include <map>
#include <iostream>
struct list
{
int a,b;
};
std::map<int,list> test_map;
int main(void)
{
std::cout <<"Testing"<< std::endl;
return 0;
}