0

This is my main.cpp


#include <iostream>
#include <unordered_map>
#include <string>
#include "myclass.h"

int main(int argc, const char * argv[]) {
    any a = myclass::returnthis();
    unordered_map<string, any>* hmap = any_cast<unordered_map<string, any>*>(a);
    return 0;
}


this is myclass.h

#ifndef myclass_h
#define myclass_h

#include <any>

using namespace std;

class myclass {
public:
    static any returnthis();
};

#endif /* myclass_h */

and this is myclass.cpp

#include "myclass.h"
#include <any>
#include <unordered_map>
#include <string>

any myclass::returnthis() {
    return new unordered_map<string, any>();
}

Now, any_cast will report bad any cast. I am working on macOS and I have tried Xcode and CLion. However, if I put the implementation of the function inside the header file, the problem vanishes. Why?

Patrik Nusszer
  • 460
  • 3
  • 13
  • 1
    `using namespace std;` in a header is a _really bad idea_. That said, its unlikely to be the cause of this issue. – Mike Vine Apr 05 '22 at 20:02
  • @MikeVine just tried out yes it is NOT – Patrik Nusszer Apr 05 '22 at 20:05
  • @FrançoisAndrieux I have corrected my question. i insist that the problem occurs for me. – Patrik Nusszer Apr 05 '22 at 20:23
  • 2
    @PatrikNusszer In the future, please try to make an example that can be copy/pasted as a single file as it makes it easier to reproduce your problem. The code shown does not cause the error you are referring to. Whatever is causing it is not shown here. Make sure you are successfully compiling the code and not accidentally running a stale executable. Try to reproduce the problem on a different system to see if you can narrow down what's missing. Edit : Works for me here : https://godbolt.org/z/9a4j77shb – François Andrieux Apr 05 '22 at 20:26
  • 1
    Is `myclass` defined in a different shared-library by any chance? In the past, this has been known to mess with RTTI -- where the internal symbol in the library sees a different instantiated value than the one in the consuming executable. Also, unrelated to your specific problem, but returning a `new`-allocated instance of `std::unordered_map` in a `std::any` object is highly suspect. `std::any` already takes care of any necessary heap allocations – Human-Compiler Apr 05 '22 at 20:37
  • @Human-Compiler The only thing I want, literally, is placing the memory address of an unordered map into an instance of std::any. Actually, the problem seems to be that the clang on macOS is buggy. My friend has tried the code on Linux, and I have also tried it on Windows. It only seems not to work on my macOS. – Patrik Nusszer Apr 05 '22 at 21:02
  • @PatrikNusszer Maybe it has to do with https://developer.apple.com/forums/thread/666516. – PixelRick Dec 16 '22 at 09:50

0 Answers0